簡體   English   中英

如何計算數組中值的總數

[英]how to calculate the total number of values in an array

我有這行代碼應該打印出數組中的項目數,但結果是只返回其中的一個。 數組示例包含兩個值 output 將是 (11) 而不僅僅是 (2)。

<?php 
if (is_array($responses) && is_countable($responses) && count($responses) > 0) {
    foreach ($responses as $val) {
        if ($val['transaction_status'] == 1) {
            echo count((array)($val['employee_name']));
        }
    }
} else {
    echo "No Active Transactions";
}

您需要在循環中求和。 目前你在每次迭代中寫1 (結果是11而不是 1+1)。

$total = 0;
if (is_array($responses) && is_countable($responses) && count($responses) > 0) {
    foreach ($responses as $val) {
        if ($val['transaction_status'] == 1) {
            $total += count((array)($val['employee_name']));
            // Is there really an array and could have more names? 
            // If no, use just $total++ instead.
        }
    }

    echo $total;
} else {
    echo "No Active Transactions";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM