简体   繁体   中英

Can the count() function work for getting the number of rows with a specific name?

I have a table types like this :

id     cat
_________

1        A

2        B

3        A

4        A

5        B

and the code i use to query the Database is something like this:

$query="SELECT*FROM types";

$res=myslqi_query($conn,$query)

while($row=myslqi_fetch_assoc($res){



          if($row['cat']==A){

               echo count($row['cat'];   

               };

}; 

i get an error with this type of code by the count()function .

Is it possible that insted of Displaying like AAA together just ti be able to display a number insted like 3 what i just want ?

Is it possible that insted of Displaying like AAA together just ti be able to display a number insted like 3 what i just want

be able to display the totall amount of the values in the 'cat' field only as a number . So if the are three Values with A that the result to be just the number 3

Try

<?php
$rows = [
 ['id'=>1, 'cat'=>'A'],
 ['id'=>2, 'cat'=>'B'],
 ['id'=>3, 'cat'=>'A'],
 ['id'=>4, 'cat'=>'A'],
 ['id'=>5, 'cat'=>'B']
];


print_r( array_count_values( array_column($rows,'cat') ) );

Output

Array
(
   [A] => 3
   [B] => 2
)

Sandbox

Where the value is the number of occurrences of each 'cat'

I don't know if that is what you want, but it's like magik.. No that was a joke it's just code.

Array Column returns only the values from a single column in a multi-dimensional array, so for this example it returns

[
   'A',
   'B',
   'A',
   'A',
   'B'
]

Then array count values, counts all the occurrences of each value in a single array, and gives us the result show at the beginning.

For this you need the whole results of the data from the database, So you can fetch them all with this while($row=myslqi_fetch_assoc($res){ and add each row to result $rows[] = $row in the loop, or you can just do $rows =mysqli_fetch_all($res,MYSQLI_ASSOC)

http://php.net/manual/en/function.array-column.php

http://php.net/manual/en/function.array-count-values.php

Of course you could also do this just in MySQL

SELECT count(id) as total FROM types GROUP BY cat.

But whatever...

Cheers Hope it helps.

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