[英]How can I search in nested arrays?
I have a variable which is containing these nested arrays: 我有一个包含这些嵌套数组的变量:
echo $var;
/* Output:
Array(
[0] => Array
(
[id] => 1
[box] => 0
)
[2] => Array
(
[id] => 2
[box] => 0
)
[3] => Array
(
[id] => 3
[box] => 1
)
) */
Now I would like to know, is there any [box] => 1
in $var
? 现在我想知道, $var
[box] => 1
是否有[box] => 1
? How can I do that? 我怎样才能做到这一点? Actually I can search in array by in_array()
function, but I don't know how can I do that for nested arrays? 实际上,我可以通过in_array()
函数在数组中进行搜索,但是我不知道如何为嵌套数组进行搜索?
You could use array_column and then array_search
: 您可以使用array_column然后再使用array_search
:
$index = array_search(1, array_column($var, 'box'));
The return value will be false
when there is no match. 如果没有匹配项,则返回值将为false
。
If you don't need to know the index of the matching element, but just need to know whether there is a match or not, then you can use in_array
: 如果您不需要知道匹配元素的索引,而只需要知道是否存在匹配项,则可以使用in_array
:
$match = in_array(1, array_column($var, 'box'));
There is another post ( Search for values in nested array ) that discusses a similar problem. 还有另一篇文章( 在嵌套数组中搜索值 )讨论了类似的问题。 The accepted answer there recommends using array_walk()
. 那里接受的答案建议使用array_walk()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.