/
array_path.php
49 lines (43 loc) · 1.17 KB
/
array_path.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
<?php
//
// Array paths (docs coming soon)
function array_path($array, $path, $default = null) {
$path = explode('.', $path);
while ($key = array_shift($path)) {
if (!isset($array[$key])) return $default;
$array = $array[$key];
}
return $array;
}
function array_path_unset(&$array, $path) {
$tmp = & $array;
$path = explode('.', $path);
while ($key = array_shift($path)) {
if (!isset($tmp[$key])) return;
$tmp = & $tmp[$key];
}
unset($tmp[array_shift($path)]);
}
function array_without_path($array) {
$args = func_get_args();
array_shift($args);
foreach ($args as $path) array_path_unset($array, $path);
return $array;
}
function array_path_replace(&$array, $path, $value) {
$tmp = & $array;
$path = explode('.', $path);
while (count($path) > 1) {
$key = array_shift($path);
if (!isset($tmp[$key])) $tmp[$key] = array();
$tmp = & $tmp[$key];
}
$tmp[array_shift($path)] = $value;
}
function array_path_to_name($path) {
$bits = explode('.', $path);
$out = array_shift($bits);
while (count($bits)) $out .= '[' . array_shift($bits) . ']';
return $out;
}
?>