This repository has been archived by the owner on May 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathutils.php
106 lines (100 loc) · 2.35 KB
/
utils.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
/**
* @file
* Helper functions for handling arrays.
* Based on Laravel helpers - https://github.com/rappasoft/laravel-helpers/blob/master/src/helpers.php
*/
/**
* Return the default value of the given value.
*
* @param $value
* @return mixed
*/
function value($value) {
return $value instanceof Closure ? $value() : $value;
}
/**
* Sets the value of an array using a doted path.
*
* @param $array
* @param $key
* @param $value
* @return mixed
*/
function array_set(&$array, $key, $value) {
if (is_null($key)) return $array = $value;
$keys = explode('.', $key);
while (count($keys) > 1) {
$key = array_shift($keys);
// If the key doesn't exist at this depth, we will just create an empty array
// to hold the next value, allowing us to create the arrays to hold final
// values at the correct depth. Then we'll keep digging into the array.
if ( ! isset($array[$key]) || ! is_array($array[$key])) {
$array[$key] = [];
}
$array =& $array[$key];
}
$array[array_shift($keys)] = $value;
return $array;
}
/**
* Gets the value of an array using a doted path.
*
* @param $array
* @param $key
* @param null $default
* @return mixed
*/
function array_get($array, $key, $default = null) {
if (is_null($key)) {
return $array;
}
if (isset($array[$key])) {
return $array[$key];
}
foreach (explode('.', $key) as $segment) {
if ( ! is_array($array) || ! array_key_exists($segment, $array)) {
return value($default);
}
$array = $array[$segment];
}
return $array;
}
/**
* Flatten a multi-dimensional associative array with dots.
*
* @param $array
* @param string $prepend
* @return array
*/
function dot($array, $prepend = '') {
$results = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$results = array_merge($results, dot($value, $prepend.$key.'.'));
}
else {
$results[$prepend.$key] = $value;
}
}
return $results;
}
/**
* Flatten a multi-dimensional associative array with dots.
*
* @param $array
* @param string $prepend
* @return array
*/
function array_dot($array, $prepend = '') {
$results = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$results = array_merge($results, dot($value, $prepend.$key.'.'));
}
else {
$results[$prepend.$key] = $value;
}
}
return $results;
}