【问题标题】:PHP Multi-Dimensional array search (with array_search)PHP多维数组搜索(带array_search)
【发布时间】:2016-05-22 07:10:45
【问题描述】:

我知道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,我如何接收 global 数组键(0 或 1) “类型”?

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

...不起作用。

【问题讨论】:

  • 你可以var_dump(array_column($response,'types'))获取输出数组这个函数。

标签: php arrays search multidimensional-array


【解决方案1】:

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

【讨论】:

  • 我还发现,array_search("whatisearchfor2", array_column(array_column($response, "types"), 0)); 也在工作。什么更好或更有效?
猜你喜欢
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
  • 1970-01-01
  • 2011-10-03
相关资源
最近更新 更多