首页 > 解决方案 > 如何递归循环遍历多维数组以获得键匹配

问题描述

我有这个变量和数组。我想遍历数组键,如果与$cat值匹配,我想获取它所属的数组键名Architecture & Design。我怎样才能做到这一点?谢谢

$cat = 'sound';

Array
(
    [Architecture & Design] => Array
        (
            [0] => architecture
            [1] => fashion
            [2] => game
            [3] => graphic
            [4] => interior
            [5] => industrial
            [6] => textile
            [7] => web
            [8] => ui
            [9] => sound
        )

    [Test array] => Array
        (
            [0] => item1
            [1] => item2
            [2] => item3
            [3] => item4
            [4] => item5
            [5] => item6
            [6] => item7
            [7] => item8
            [8] => item9
            [9] => item0
        )

)

标签: phparrays

解决方案


您可以将 next 函数与 foreach 循环一起使用:

$cat = 'sound';

function get_key($array,$cat){

    foreach($array as $key=>$subar){

        foreach($subar as $val){
            if ($val === $cat) return $key;  
        }  

    }
    return '';
}

echo get_key($data,$cat);

它会给你带来第一个外观。

演示


推荐阅读