PHP多维数组搜索(带array_search)

时间:2016-02-11 13:22:54

标签: php arrays search multidimensional-array

我知道this question,但我还有一个搜索数组键。看看这个:

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"
    }
  }
}

This snippet ...

echo array_search("Text 2", array_column($response, "name"));

...给我第二个数组键1,其中找到了术语。

但如果我搜索存储在多数组中的 whatisearchfor2 ,我如何收到全局数组键(0或1)? “类型” 吗

echo array_search("whatisearchfor2", array_column($response, "types"));

......不起作用。

1 个答案:

答案 0 :(得分:2)

在您的情况下,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)