php - 如何递归循环遍历多维数组以获得键匹配
问题描述
我有这个变量和数组。我想遍历数组键,如果与$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
)
)
解决方案
您可以将 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);
它会给你带来第一个外观。
推荐阅读
- swift - MacCatalyst 上的核心数据 CloudKit 同步问题
- vba - 如何解决 MS Access 中的错误 - VBA SQL 执行?
- c - 从另一个双指针中减去一个双指针的值是什么意思?
- powerquery - 根据不同的选择,特定列的双重数据类型?
- reactjs - webpack cli什么时候开始发挥作用
- python - 如何在python中使用精度计算浮点数
- python - 如何在 nn.LSTM pytorch 中获得 R2 分数
- swift - 无法从其他应用打开 tvOS 上的通用链接
- javascript - 将值传递给承诺中的另一个变量不起作用
- python - 如何在嵌套结构中存储层次结构信息