-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataFinder.php
98 lines (81 loc) · 2.58 KB
/
DataFinder.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
<?php
namespace Atompulse\Component\Data;
/**
* Class Data Finder
* Data Structures Helper
* @package Atompulse\Component\Data
*
* @author Petru Cojocar <petru.cojocar@gmail.com>
*/
class DataFinder
{
/**
* Search in multidimensional array and return an array path of keys to the searched item
* @param string $needle
* @param array $haystack
* @param string $needleKey
* @param boolean $strict
* @param array $path
* @return mixed
*/
public static function searchRecursive($needle, $haystack, $needleKey = "", $strict = false, $path = [])
{
if (!is_array($haystack)) {
return false;
}
foreach ($haystack as $key => $val) {
if (is_array($val) &&
$subPath = self::searchRecursive($needle, $val, $needleKey, $strict, $path)
) {
$path = array_merge($path, [$key], $subPath);
return $path;
} elseif ((!$strict && ($val == $needle || is_null($needle)) &&
$key == (strlen($needleKey) > 0 ? $needleKey : $key)) ||
($strict && $val === $needle &&
$key == (strlen($needleKey) > 0 ? $needleKey : $key))
) {
$path[] = $key;
return $path;
}
}
return false;
}
/**
* Given a path array structure (i.e. returned by searchRecursive) this function
* retrieves the actual value from a target array (the returned value can be single or a complex structure)
* @param array $pathKeys
* @param array $source
* @return mixed
*/
public static function getFromPath($pathKeys, $source)
{
$mappedValue = $source;
foreach ($pathKeys as $key) {
if (isset($mappedValue[$key])) {
$mappedValue = $mappedValue[$key];
} else {
return false;
}
}
return $mappedValue;
}
/**
* Given a path array structure (i.e. returned by searchRecursive) this function
* retrieves the actual value from a target array (the returned value can be single or a complex structure)
* @param array $pathKeys
* @param array &$source
* @return mixed
*/
public static function removeFromPath($pathKeys, &$source)
{
$mappedValue = $source;
foreach ($pathKeys as $key) {
if (isset($mappedValue[$key])) {
$mappedValue = $mappedValue[$key];
} else {
return false;
}
}
return $mappedValue;
}
}