forked from maciejczyzewski/bottomline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
patch.php
38 lines (32 loc) · 844 Bytes
/
patch.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
<?php
namespace arrays;
/**
* Patches array by xpath.
*
** __::patch(['addr' => ['country' => 'US', 'zip' => 12345]], ['/addr/country' => 'CA', '/addr/zip' => 54321]);
** // → ['addr' => ['country' => 'CA', 'zip' => 54321]]
*
* @param array $arr The array to patch
* @param array $patches List of new xpath-value pairs
* @param string $parent
*
* @return array Returns patched array
*
*/
function patch($arr, $patches, $parent = '')
{
foreach ($arr as $key => &$value) {
$z = $parent . '/' . $key;
if (isset($patches[$z])) {
$value = $patches[$z];
unset($patches[$z]);
if (!count($patches)) {
break;
}
}
if (is_array($value)) {
$value = patch($arr[$key], $patches, $z);
}
}
return $arr;
}