I need to return a value from a multidimensional array based on key.
Basically i don't want to create 2 or 3 for loops, because the array can be nested like endless.
Example of my array
$menu = Array
(
[16] => Array
(
[categories_id] => 16
[categories_name] => Recorders
[parent_name] => Recorders
[children] => Array
(
[23] => Array
(
[categories_id] => 23
[categories_name] => Security
[parent_name] => Recorders - Security
[children] => Array
(
[109] => Array
(
[categories_id] => 109
[categories_name] => 4CH NVR
[parent_name] => Recorders - Security - 4CH NVR
)
[110] => Array
(
[categories_id] => 110
[categories_name] => 8CH NVR
[parent_name] => Recorders - Security - 8CH NVR
)
I found another solution which almost works:
function findParentNameFromCategory($obj, $search)
{
if (!is_array($obj) && !$obj instanceof Traversable) return;
foreach ($obj as $key => $value) {
if ($key == $search) {
return $value['parent_name'];
} else {
return findParentNameFromCategory($value, $search);
}
}
}
The problem with this is that it just echo the value. I need to assign the value to a var. If i changed echo to return i didn't get any value back at all.
$test = findParentNameFromCategory($menu, 109);
when i echo $test i don't have any value at all