数组中的数字,其中键是整数,php

时间:2011-11-30 22:41:17

标签: php arrays

我的代码:

foreach($comment as $key => $value) {

$total = $value['likes'];

echo "$key: $total\n"

}

输出:

  

0:3 1:18 2:72 3:0 4:10 5:0 6:0 7:0 8:0 9:0 10:0 11:19 12:0 13:0 14:14 15: 19 16:0 17:0 18:1

如何汇总所有值? array_sum函数给出“警告:期望参数1为数组,给定整数”。

4 个答案:

答案 0 :(得分:1)

如果你想这样做,你需要从变量开始并继续添加变量。

$total = 0;

foreach($comment as $key => $value) {

   $total += $value['likes'];

}

echo "The sum is: " . $total;

答案 1 :(得分:1)

$sum = 0;
foreach($comment as $key=>$value) {
   $sum+=$value;
}

echo "Total: $sum";

答案 2 :(得分:1)

Array_sum期待单维数组。从代码的外观来看,你有一个多维数组。其中$ value也是一个数组。

你对总数有正确的想法,但你必须像$total = $total + $value['likes']或短篇版$total += $value['likes']那样添加总数:

$total = 0;

foreach($comment as $key => $value) {

    $total += $value['likes'];

    echo "$key: $total\n"

}

echo "My total is: $total";

答案 3 :(得分:0)

保持总计......

$total_likes = 0;

foreach($comment as $key => $value) {

    $total = $value['likes'];
    $total_likes += $total;

    echo "$key: $total\n"

}

echo "Total: $total_likes \n";