doupao3662 2018-10-03 01:51
浏览 14
已采纳

count()函数可以用于获取具有特定名称的行数吗?

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 ?

  • 写回答

1条回答 默认 最新

  • doubi1910 2018-10-03 03:34
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值