Leon Armstrong Leon Armstrong - 1 month ago 13
PHP Question

How to search array at certain depth?

I am having a multidimensional array with many depth , since I have around 9 dimension so I going to show my code on how I accessing them

sample code:

$attribute[5]['group'][1]['f'][4]['id'][18]['fc'][20]


sample array

Is there any way to get the array base on the depth and key I want , without knowing the level before it

lets say I have only partial information like key 20(the last key) , Is there any way to get the array at the 9th dimension with key 20?

Ideal function should look like this

function get_by_depth($m_array,$depth,$key){

}

$array=get_by_depth($attribute,9,20);
//will search through available level 9 item
//if there are key 20 at level 9 return the array or value

Answer

Something like this could work using your sample array data.

function get_by_depth($array, $depth, $key, $currentDepth = 0)
{
    if ($currentDepth == $depth) {

        return isset($array[$key]) ? $array[$key] : null;

    } else {

        foreach ($array as $k => $v) {

            if (is_array($v)) {
                return get_by_depth($v, $depth, $key, ++$currentDepth);
            }

        }

    }

}


echo "<pre>";
print_r(get_by_depth($array,8,'image'));exit;

Note This assumes that every array only contains at most a single array inside of it. If you need a solution that can handle arrays that contain multiple arrays at the same level of depth then there would be a lot more work to do