My question is similar to Searching for an array key branch inside a larger array tree - PHP, but for different limitations (like processing on the fly, etc) and why not for knowledge sake I would like to implement it using just PHP recursion.
Consider this data:
array(
'root_trrreeee1' => array(
'path1' => array(
'description' => 'etc',
'child_of_path_1' => array(
array('name' => '1'),
array('name' => '1')
)
),
'path1' => array(
'description' => 'etc',
'child_of_path_1' => array(
array('name' => '1'),
array('name' => '1')
)
),
),
'name' => '1',
1 => array('name' => '1'),
'another_leaf' => '1'
)
If I search for array('name' => '1')
it should return the path I need to traverse to get to that value root_trrreeee1.path1.child_of_path_1.o
, preferably returned as array:
array(
0 => root_trrreeee1
1 => path1
2 => child_of_path_1
3 => 0
)
This is the recursive function I've tried to implement but its not working:
function multidimensional_preserv_key_search($haystack, $needle, $path = array(), &$true_path = array())
{
if (empty($needle) || empty($haystack)) {
return false;
}
foreach ($haystack as $key => $value) {
foreach ($needle as $skey => $svalue) {
if (is_array($value)) {
$path = multidimensional_preserv_key_search($value, $needle, array($key => $path), $true_path);
}
if (($value === $svalue) && ($key === $skey)) {
$true_path = $path;
return $true_path;
}
}
}
if (is_array($true_path)) { return array_reverse(flatten_keys($true_path)); }
return $path;
}
function flatten_keys($array)
{
$result = array();
foreach($array as $key => $value) {
if(is_array($value)) {
$result[] = $key;
$result = array_merge($result, self::flatten_keys($value));
} else {
$result[] = $key;
}
}
return $result;
}
it returns just an empty array. Thanks in advance.
Similar questions I've found:
- Searching for an array key branch inside a larger array tree - PHP
- Find a value & key in a multidimensional array
- Find all second level keys in multi-dimensional array in php
- Find an array inside another larger array
- How to search by key=>value in a multidimensional array in PHP
- Searching for a key in a multidimensional array then changing a value with PHP
- How can I find the locations of an item in a Python list of lists?