【问题标题】:how to count duplicates values inside while loop using php如何使用php计算while循环内的重复值
【发布时间】:2015-05-23 09:04:14
【问题描述】:

$query = "从表项中选择 *";
$result = mysql_query($query);

$col = array();

while ($row = mysql_fetch_array($result)){

 //they have computation here inside loop.
  $amount = $value;

if($row['status']>3){  // base on the status only
    if($amount>0){ //base on the computation 

        $count = $item;
        // i need to count here the item before the grouping of duplicate item below.

    if (!isset($col[$row['item']])) { // this is working for grouping the duplicate value
       echo $row['item'];  
       echo $count;   // count item 
       $col[$row['item']] = true;
      }
   }
 }}

如果可能,在 while 循环中的示例输出应该是这样的。

项目一 2
项目二 3
第五项 4

【问题讨论】:

    标签: php count


    【解决方案1】:

    你可以用sql而不是php来做到这一点;

    SELECT COUNT(*) as N,item 
    FROM tableitem
    GROUP BY item
    

    它将返回重复的项目,您可以通过n>1 进行检查。您可以为组添加更多列。

    $itemArray;
    while ($row = mysql_fetch_array($result)){
        if($row['n']>1){
           itemArray[] = $row['item'];    
        }    
    }
    print_r($itemArray);
    

    【讨论】:

    • tnkyou 飓风,但我很抱歉包括我在循环内有计算。所以基于计算和条件,这只是我计算项目的时间。
    【解决方案2】:

    如果您使用要计数的键来增加数组值:

    $check = array();
    foreach($values as $key => $value) {
       if (isset($check[$key])) {
           $check[$key]++;
       } else {
           $check[$key]=1;
       }
    }
    var_dump($check); 
    

    【讨论】:

    • 谢谢尼古拉斯。我试图根据上面的代码来计算项目
    猜你喜欢
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 2021-11-09
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多