Best way to do array_search on multi-dimensional array?

Best way to do array_search on multi-dimensional array?

$array[‘key1’][‘key2’][‘key3’] = “hello”;

So, somehow, I provide “hello” and it returns array(‘key1’, ‘key2’, ‘key3’); - that would be ideal.

There are a lot of user comments in the PHP docs that can help you with questions such as this, see the below link.

http://www.php.net/manual/en/function.array-search.php#106904

Thanks, but the link you posted to does the opposite of what I want.

I can’t find anything on there that does what I want it to, they all seem to be the same way as the link you posted.

The link would allow providing ‘key1’, ‘key2’, ‘key3’ and returning ‘value’


$array['key1']['key2']['key3'] = "value";

…but I want to provide ‘value’ and return key1, key2, key3 etc.

Thanks for posting though.

Have a look through the docs page as i went down the page and found quite a few more comments with some handy functions that might help. Also i doubt you would be able to find an exact code source for what your wanting as retrieving the index for a specific search is faster then storing each key index.


function array_find_deep($array, $search, $keys = array())
{
    foreach($array as $key => $value) {
        if (is_array($value)) {
            $sub = array_find_deep($value, $search, array_merge($keys, array($key)));
            if (count($sub)) {
                return $sub;
            }
        } elseif ($value === $search) {
            return array_merge($keys, array($key));
        }
    }

    return array();
}

$a = array(
    'key1' => array(
        'key2' => array(
            'key3' => 'value',
            'key4' => array(
                'key5' => 'value2'
            )
        )
    )
);

var_dump(array_find_deep($a, 'value'));
/*
array
  0 => string 'key1' (length=4)
  1 => string 'key2' (length=4)
  2 => string 'key3' (length=4)
*/

var_dump(array_find_deep($a, 'value2'));
/*
array
  0 => string 'key1' (length=4)
  1 => string 'key2' (length=4)
  2 => string 'key4' (length=4)
  3 => string 'key5' (length=4)
*/

var_dump(array_find_deep($a, 'value3'));
/*
array
  empty
*/

:slight_smile: