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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line