Find path of the given array key?

Hi,

I have a very big multi dimenssional array and in that I have a key name of which I need to find the path so I can access it directly.
How do I search for keys using text search “some key” and it should show the path of all the matching keys.

So if i search for “some key”

then it should give result something like:

array[“level0”][“level1”][“somekey”] or something similar so that I know what is its path and how to access it directly.

Please help.

Thanks.

Go to this page and search on the phrase “This function will extract keys from a multidimensional array”. There you will find someone has done two-thirds (if not all) of the work for you.

Hi,

Thanks for the response but it just lists all the keys, i can already do that using print_r…what I want to achieve to find a specific key’s path in the multi dimensional array. If you look at the example provided by the function creator, it just lists the size array as 0,1,2 where as I want to find to which parent array it belongs to or maybe get its full array path from starting eg.: size > 0, size > 1, size > 2

Thanks.

Something like this might work.

<?php
//example
//array["level0"]["level1"]["somekey"]
$input = array();
$input['level0']['level1']['somekey'] = "value of somekey";
$input['level0']['level1']['somekey2'] = "value of somekey2";
$input['level0']['level1b']['somekey1b'] = "value of somekey1b";
$input['level0']['level1']['level2']['somekey1c'] = "value of somekey1c";
//test search value
$search_value = "somekey1c";	


	
function getkeypath($arr, $lookup)
{
    if (array_key_exists($lookup, $arr))
    {
        return array($lookup);
    }
    else
    {
        foreach ($arr as $key => $subarr)
        {
            if (is_array($subarr))
            {
                $ret = getkeypath($subarr, $lookup);

                if ($ret)
                {
                    $ret[] = $key;
                    return $ret;
                }
            }
        }
    }
    return null;
}
	
$pathresult = getkeypath($input, $search_value);
krsort($pathresult);
$path = array();
$cur = &$path;
foreach ($pathresult as $value) {
    $cur[$value] = array();
    $cur = &$cur[$value];
}
$cur = null;

echo "<pre>";
print_r($path);
echo "</pre>";	
?>
Array
(
    [level0] => Array
        (
            [level1] => Array
                (
                    [level2] => Array
                        (
                            [somekey1c] =>
                        )

                )

        )

)