-1

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

poNgz0r
  • 69
  • 1
  • 8

2 Answers2

2
array_walk_recursive($obj, function(&$v, $k){
        if($k == $search)
           return $v['parent_name'];
   });
Shanteshwar Inde
  • 1,438
  • 4
  • 17
  • 27
1

in your fix you forgot about the else case. so you should return the value of recursive call also:

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);
        }

        if ($return !== null) {
            return $return;
        }
    }
}
myxaxa
  • 1,391
  • 1
  • 8
  • 7