PHP 多维数组搜索键

$list[7362][0]['value'] = 'apple';

$list[7362][1]['value'] = 'orange';

$list[9215][0]['value'] = 'lemon';

我想要值“橙色”的键。我尝试使用 array_search 和 array_column,但显然我有问题 array_column。


$key = array_search('orange', array_column($list, 'value'));

如上所述


PHP多维数组按值搜索

但我的情况略有不同。密钥应返回 7362。


繁华开满天机
浏览 161回答 2
2回答

慕工程0101907

你可以尝试这样的事情:<?php$list = array();$list[7362][0]['value'] = 'apple';$list[7362][1]['value'] = 'orange';$list[9215][0]['value'] = 'lemon';foreach ($list as $keynum=>$keyarr) {&nbsp; &nbsp; foreach ($keyarr as $key=>$index) {&nbsp; &nbsp; &nbsp; &nbsp; if (array_search('orange', $index) !== false) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo "orange found in $key >> $keynum";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; }&nbsp; &nbsp;}?>您可以选择只回显echo $keynum;您的目的。遍历数组并找出找到的位置orange。您可以将其重构为如下函数:<?phpfunction getKeys($list, $text) {&nbsp; &nbsp; foreach ($list as $keynum=>$keyarr) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; foreach ($keyarr as $key=>$index) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (array_search($text, $index) !== false) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "$text found in $key >> $keynum";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return "not found";}$list = array();$list[7362][0]['value'] = 'apple';$list[7362][1]['value'] = 'orange';$list[9215][0]['value'] = 'lemon';echo getKeys($list, 'lemon');?>echo getKeys($list, 'lemon');会给你lemon found in 0 >> 9215。echo getKeys($list, 'orange');会给你orange found in 1 >> 7362。echo getKeys($list, 'apple');会给你apple found in 0 >> 7362。

largeQ

它array_column在该级别嵌套到很远,因此只需循环:foreach($list as $k => $v) {&nbsp; &nbsp; if(in_array('orange', array_column($v, 'value'))) {&nbsp; &nbsp; &nbsp; &nbsp; $key = $k;&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}如果可以有多个则创建一个数组并且不要break:&nbsp; &nbsp; &nbsp; &nbsp; $key[] = $k;&nbsp; &nbsp; &nbsp; &nbsp; //break;
打开App,查看更多内容
随时随地看视频慕课网APP