简体   繁体   English

如何计算数组中值的总数

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

i have this line of code that is supposed to print out the number of items in an array but rather the result is return only ones of the number.我有这行代码应该打印出数组中的项目数,但结果是只返回其中的一个。 Example of the array contains two values the output will be (11) instead of just (2).数组示例包含两个值 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";
}

You need to make a sum in the loop.您需要在循环中求和。 Currently you write there 1 in each iteration (it results in 11 instead of 1+1).目前你在每次迭代中写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