php 每个循环条件总计

php for each loop conditional total

我有一个 foreach 循环,我正在尝试获取工作正常的总计数值。但问题是,数据库中的大多数 hard_disk3 列行都包含值 "None",我希望 php 不计算行值为 "None".[=12= 的地方]

这是 php 代码,我该怎么做才能实现?

<?php
    $type="systype, hard_disk3";
    $typeQuery = $basequery." GROUP BY ".$type;
    // Perform the Query
    $objDbResultByType = $objDatabase->Query($typeQuery);
    $imran9 = array();
    foreach ($objDbResultByType as $row) {

        $result = "{ label: \"".$row['systype']." ".$row['hard_disk3']."\", y: " .$row['total']." },";
        array_push($imran9,$result);
    }
    $lastIndex = count($imran9)-1;
    $lastValue = $imran9[$lastIndex];
    $imran9[$lastIndex] = rtrim($lastValue, ',');
?>

您应该只在 SQL 查询中指定它。 SELECT COUNT(hard_disk3) FROM table WHERE hard_disk3 != "None" 这样你的 dbms 只是 returns 总行数,你既不需要 foreach 循环也不需要 PHP 做任何真正的工作来得到你的结果。

您可以通过两种方式实现此目的,第一种已由 Sherif 提及(这是更好的方法),第二种在 PHP 中非常简单。试试这个:

<?php
    $type="systype, hard_disk3";
    $typeQuery = $basequery." GROUP BY ".$type;
    // Perform the Query
    $objDbResultByType = $objDatabase->Query($typeQuery);
    $imran9 = array();
    foreach ($objDbResultByType as $row) {
        if ($row['hard_disk3'] == "None") 
        {
            continue;
        }
        $result = "{ label: \"".$row['systype']." ".$row['hard_disk3']."\", y: " .$row['total']." },";
        array_push($imran9,$result);
    }
    $lastIndex = count($imran9)-1;
    $lastValue = $imran9[$lastIndex];
    $imran9[$lastIndex] = rtrim($lastValue, ',');
?>

或者您可以尝试:

if ($row['hard_disk3'] != "None") {
    $result = "{ label: \"".$row['systype']." ".$row['hard_disk3']."\", y: " .$row['total']." },";
    array_push($imran9,$result);
}