简体   繁体   中英

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 ? 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?

well, you could simply use a foreach loop, as a clear and simple way, like::

foreach($arr as $key => $val) {
    if($val["box"] == 1) {
        echo "Found";
    }
}

You could use array_column and then array_search :

$index = array_search(1, array_column($var, 'box'));

The return value will be false when there is no match.

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 :

$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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM