PHP数组保存数据并按其索引计算

时间:2015-12-01 04:23:50

标签: php arrays

我在数组中有一个数字列表。这是我的示例数据:

Person 1 => 20, 40, 50
Person 2 => 10, 20, 40
Person 3 => 20, 20, 30

我想问一下,如何将他们的分数放入数组并按其索引计算?我创建这个数组的代码:

$indeksarr = 1;
$temparr[$indeksarr] = array();
$num = 3;

while($grade = $query->fetch_array()) <-- basically get score from DB (only return score for each student)
{
   for($i=1; $i <= $num; $i++)
   {
      $newdata = array($indeksarr => $grade);
      $temparr[$indeksarr][] = $newdata;
      $indeksarr++;
   }
}
for($i=1; $i <= $num; $i++)
{
   print_r($temparr[$i]);
}

我的代码结果:

Result[1] = 20
Result[2] = 10

我想要的结果:

Result[1] = 50 ( <- 20+10+20 ) <- all from array index 1
Result[2] = 80 ( <- 40+20+20 ) <- all from array index 2
Result[3] = 120 ( <- 50+40+30 ) <- all from array index 3

有什么想法来修复我的阵列吗?

4 个答案:

答案 0 :(得分:2)

请尝试下面的代码一次,它也可能有助于动态值。

 while ($grade = $query->fetch_array()) {
    //$grdata = explode(",", $grade); // if those are comma separated values
    $grdata =  $grade;
    for ($j = 0, $k = 1; $j < count($grdata); $j++, $k++) {
        if (isset($temparr[$k])) {
            $temparr[$k] = $temparr[$k] + $grdata[$j];
        } else {
            $temparr[$k] = $grdata[$j];
        }
    }
}
print_r($temparr);

答案 1 :(得分:0)

试试这个:

$result = array();
$start_index = 1;
$stop_index = 3;
while($grade = $query->fetch_array()) //<-- basically get score from DB (only return score for each student)
{
// grade = array('Person 1' => array(20,10,20));
   $values = array_values($grade);
   $result[$start_index] = array_sum($values[0]);

   if ($start_index == $stop_index) break; // stop when it reach stop_index
   $start_index++;
}

echo "<pre>";
print_r($result);
echo "</pre>";
die;

答案 2 :(得分:0)

biuld数组如下

 $persons = array('Person1'=>array(20,40,50),'Person2' => array(10, 20, 40),'Person3' => array(20, 20, 30));

//than perform below function

$array_sum = array_reduce($persons,"abb");
  function abb($a,$b)
{
    foreach($b as $key=>$value)
    {
       if(isset($a[$key]))
        $a[$key] += $value;
        else
        $a[$key] = $value;
    }
    return $a;
}

var_dump($array_sum);

O / P

array (size=3)
  0 => int 50
  1 => int 80
  2 => int 120

答案 3 :(得分:0)

以下是使用array_walkarray_sum的简单替代方法:

$subTotal = [[0,0,0],[0,0,0],[0,0,0]];
$line = 0;

function walk($item, $key) {
    global $subTotal;
    global $line;
    $subTotal[$key][$line] = $item;
}

$array = [
    [20, 40, 50],
    [10, 20, 40],
    [20, 20, 30]
];
$finalArray = [];

array_walk($array[0], 'walk');
$line = 1;

array_walk($array[1], 'walk');
$line = 2;

array_walk($array[2], 'walk');

$finalArray[] = array_sum($subTotal[0]);
$finalArray[] = array_sum($subTotal[1]);
$finalArray[] = array_sum($subTotal[2]);

// Will print '50, 80, 120, '
foreach($finalArray as $total) {
    echo $total.', ';
}

希望这有帮助!