views:

310

answers:

2

Perhaps someone can help me out with this one:

I'm using a basic search function to find an array deep within an array. The problem is, once that array is found, I'd also like to return it's parent key. Is there a PHP function that can determine the parent key of an array?

Below is an example of the Search Function... Ideally I'd like to return the array that is found, as well as it's parent key.

    function search($array, $key, $value){
    $results = array();

    if (is_array($array)){
        if ($array[$key] == $value){
            $results[] = $array;
        }
        foreach ($array as $subarray){
            $results = array_merge($results, search($subarray, $key, $value));
        }   
    }

    return $results;
}

HERE IS AN EXAMPLE TO BETTER ILLUSTRATE WHAT I MEAN: Here is an example of an array I'd like to search:

    Array
(
    [categories] => Array
        (
            [1] => Array
                (
                    [data] => 
                    [id] => d
                    [name] => Bracelets
                    [products] => Array
                        (
                            [0] => Array
                                (
                                    [id] => j
                                    [name] => Red
                                    [data] => 
                                )

                            [1] => Array
                                (
                                    [id] => gi
                                    [name] => Torqoise
                                    [data] => 
                                )

                        )

                )

If I search for something with the 'id' of "j", I would get this array as the result:

Array
(
    [0] => Array
        (
            [id] => j
            [name] => Red
            [data] => 
        )

)

Now, ideally I would also like to know the parent key of this Array, which in the example is 'Products', which I obviously would need to retrieve before returning the results...

+1  A: 

No, there is no built in function. You can pass parent key in the function params

Col. Shrapnel
@Jordan How's that? Just use extended syntax of foreach and you'll have it
Col. Shrapnel
A: 

You could use array_flip() to swap the key and values so you can retrieve the key with the value.

You could also slightly modify your foreach to something like

foreach ($array as $subarray_key => $subarray){
  $results = array_merge($results, search($subarray, $key, $value));
}

and $subarray_key would be the key.

Jamza