我知道
这个问题,但我还有一个额外的问题要搜索数组键。看看这个:
array(2) {
[0]=>
array(2) {
["name"]=>
string(6) "Text 1"
["types"]=>
array(3) {
[0]=>
string(7) "Level 1"
[1]=>
string(14) "something else"
[2]=>
string(15) "whatisearchfor1"
}
}
[1]=>
array(2) {
["name"]=>
string(6) "Text 2"
["types"]=>
array(3) {
[0]=>
string(7) "Level 2"
[1]=>
string(14) "something else"
[2]=>
string(15) "whatisearchfor2"
}
}
}
这个片段...
echo array_search("Text 2", array_column($response, "name"));
。给我一个 1 表示第二个数组键,其中找到了该术语。
但是,如果我搜索存储在多数组"类型"中的 whatisearchfor2,我如何接收全局数组键(0 或 1)?
echo array_search("whatisearchfor2", array_column($response, "types"));
。不行。
在您的情况下array_column($response, "types")
将返回一个数组数组。但是要获取"全局数组键(0 或 1),如果您搜索 whatisearchfor2",请使用以下方法array_walk
:
$key = null; // will contain the needed 'global array-key' if a search was successful
$needle = "whatisearchfor2"; // searched word
// assuming that $arr is your initial array
array_walk($arr, function ($v,$k) use(&$key, $needle){
if (in_array($needle, $v['types'])){
$key = $k;
}
});
var_dump($key); // outputs: int(1)