views:

528

answers:

2

I'm trying to find a way to return the value of an array's parent key.

For example, from the array below I'd like to find out the parent's key where $array['id'] == "0002". The parent key is obvious because it's defined here (it would be 'products'), but normally it'd be dynamic, hence the problem. The 'id' and value of 'id' is known though.

    [0] => Array
        (
            [data] => 
            [id] => 0000
            [name] => Swirl
            [categories] => Array
                (
                    [0] => Array
                        (
                            [id] => 0001
                            [name] => Whirl
                            [products] => Array 
                               (
                                    [0] => Array
                                        (
                                            [id] => 0002
                                            [filename] => 1.jpg
                                         )
                                    [1] => Array
                                        (
                                            [id] => 0003
                                            [filename] => 2.jpg
                                         )
                                )
                         )
                 )
          )
+1  A: 

Since you have a tree structure either of a BFS or DFS can do it. Since the structure is variable a recursive solution would work well. Simply return a sentinel when you find the value, then return the key in the caller.

Ignacio Vazquez-Abrams
+1  A: 

A little crude recursion, but it should work:

function find_parent($array, $needle, $parent = null) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $pass = $parent;
            if (is_string($key)) {
                $pass = $key;
            }
            $found = find_parent($value, $needle, $pass);
            if ($found !== false) {
                return $found;
            }
        } else if ($key === 'id' && $value === $needle) {
            return $parent;
        }
    }

    return false;
}

$parentkey = find_parent($array, '0002');
deceze
I'm not too familiar with recursion, but I coded up a similar answer to this, only I used a 'static' variable to replace the `$parent` argument you use. Is either way better?
alex
@alex `static` would probably work fine as well. I have to admit I'm not much of a `static` user. :) It'd eliminate the need to pass along the extra variable. OTOH, in the above function you can specify a "default" parent... Either one's okay I guess. :)
deceze
Thanks, I understand the benefits of your method. +1
alex