简体   繁体   中英

How can I filter a multidimensional array and count the filtered values?

I have an array coming from a mysql database. So it is structured this way (just the first two entry):

Array
(
    [0] => Array
        (
            [id_cre] => CD000000001
            [0] => CD000000001
            [id_az] => AZ000000001
            [1] => AZ000000001
        )

    [1] => Array
        (
            [id_cre] => CD000000002
            [0] => CD000000002
            [id_az] => 
            [1] => 
        )
)

I would like to count how many entries in the array have [id_az] =>'' .

If I do:

count($creds)

I get 2 (the number of items in the array).

I'd prefer to reuse this array (the query runs already for another report), instead of doing a new query with the WHERE clause to subselect WHERE id_az = '' .

Any hint(s)?

This should work for you:

Just get the column id_az with array_column() and count() the array then, eg

echo count(array_column($creds, "id_az"));

Why not use a good old foreach loop?

$count = 0;
foreach($data as $row)
{
  $count += empty($row['id_az']) ? 0 : 1;
}

or alternativly an array_map with a anonymous function

$count = 0;
array_map(function($row) use (&$count) { $count += empty($row['id_az']) ? 0 : 1; }, $data);

But this is PHP >5.3. Callbacks won't work, since you won't have access to a variable to store your count in.

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