-1

嗨,对于以下情况,如何从 foreach 循环中获取总和:

price = Array
(
    [0] => Array
        (
            [0] => 100
            [1] => 200
        )

    [1] => Array
        (
            [0] => 300
            [1] => 400
        )
)

我怎样才能得到每个元素的平均值和?我需要补充

avg1 = price[0][0] + price[1][0] .... + price[N][0]
avg2 = price[0][1] + price[1][1] .... + price[N][1]

然后除以元素数。谢谢

4

3 回答 3

2

试试这个

<?php


 $price = array
(
    0 => array
        (
            0 => 100,
            1 => 200,
        ),

    1 => array
        (
            0 => 300,
            1 => 400,
        )
);
$a = 0;
$b = 0;
$i  = 0;
foreach($price as $p)
{
    $a += $p[0];
    $b += $p[1];
    $i++;
}
echo 'Avg of a= '. ($a/$i).PHP_EOL;
echo 'Avg of b= '. ($b/$i).PHP_EOL;
?>

这是一个简单的线索....您可以按照自己的想法构建它

于 2013-04-06T03:12:50.703 回答
0
<?php
$price = array();
$price[0][0] = 100;
$price[0][1] = 200;
$price[1][0] = 300;
$price[1][1] = 400;
$price[2][0] = 500;
$price[2][1] = 600;

$sum1 = 0; $sum2 = 0;
$count1 = 0; $count2 = 0;

foreach($price as $array){
   if (isset($array[0])){
      $sum1+=$array[0];
      $count1++;
   }
   if (isset($array[1])){
      $sum2+=$array[1];
      $count2++;
   }
}

$ave1 = sprintf("%2.f", $sum1/$count1);
$ave2 = sprintf("%2.f", $sum2/$count2);
print "$ave1\n$ave2\n\n";
?>
于 2013-04-06T03:35:13.493 回答
0
for($i =0; $i < count($i): $i++){
   $avg = 0;
   for($j =0; $i < $j: $j++){
        $avg = $avg + $price[$j][$i] ;        
   }
   echo "avg$i: $avg";
}
于 2013-04-06T05:09:25.023 回答