简体   繁体   中英

Count number of rows with specific value of array

So i have an array, it has 1000 rows, and a column contains the age of a user, im trying to determine how to count the amount of rows for people who are <17, 17-25, 26-40 etc.

I know this is possible with a for loop:

for($i=0,$i<$totalrows,$i++)
    $birthdate=$array[$i][birthdate];
    if($birthdate>1995)
    {
        $seventeen=$seventeen+1;
    }
    elseif
    {
        etc...

but is there a built in function that can do this instead of needing to do a for loop to calculate all the values? Once the count got to millions wouldn't this become quite taxing on the server?

edit/ should i be doing this with like 5 different SQL Selects? just using a count(*)? would that be more efficient?

You could use array_filter() and then count() the return values from that.

$seventeen = count(array_filter($array,
                                function ($entry) { 
                                    return ($entry['birthdate'] > 1995); 
                                }
                               )
                  )

NB Unless you have defined "birthdate" as a constant, you should quote it so that's it's treated as a string

you could do the counting using sql while fetching the data. As far as processing performance goes, it all depends on the query requests.

As for PHP goes, what you could do is create a multi-dimensional array.

$arr = array(
    '0-16' => array(

    ),
    '17-25' => array(

    ),
    '26-40' => array(

    )
);

and when you fetch a group add them to a group

while ($query as $result) {
    if ($result['age'] < 17) {
        $arr['0-16']['age'] = $result['age'];
        $arr['0-16']['name'] = $result['name'];
    }
}

then do a count

echo count($arr['0-16'])

this way you can always print_r the array that has the group you want and further manipulate that group.

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