PHP 获取数组中每n个元素的总和

PHP Get total of every n elements in array

我正在使用一个 API returns JSON 类似于下面的数组。如图所示,每个 ID 都是十进制的。我需要打印出 ID.x 的每个元素(根据 ID 的整数)和每个元素的标记,然后是总数。 (例如输出:
ID 0.1 = 2 mks
ID 0.2 = 4 mks
ID 0.3 = 1 mks
ID 0 total = 7

ID 1.1 = .......).

<?php
$sampleArray = array(
  
    array("id"=>0.1, "marks"=>2),
    array("id"=>0.2, "marks"=>4),
    array("id"=>0.3, "marks"=>1),
    array("id"=>1.1, "marks"=>6),
    array("id"=>1.2, "marks"=>0),
    array("id"=>1.3, "marks"=>8),
    array("id"=>2.1, "marks"=>7),
    array("id"=>2.2, "marks"=>12),
);
 
$arrayLength = count($sampleArray);

$i = 0;
$x = 0;

while ($i < $arrayLength){
    $sum = 0;
 
    $idWhole = floor($sampleArray[$i]['id']);
    if(idWhole == $x){
        $sum += $sampleArray[$i]['marks'];
        echo 'id: '.$sampleArray['id'].', marks: '.$sampleArray[$i]['marks'].'<br>';
    }else{
        echo '<br>Sum of ID $idWhole is $sum<br>'; 
        $x++;
    }  
    $i++;
}

?>

好消息,您不需要转换任何东西——当您将浮点值用作输出数组中的键时,PHP 将强制您的浮点值是整数(truncate/floor 值) .

循环求和。

代码:(Demo)

$result = [];
foreach ($sampleArray as $row) {
    $result[$row['id']] = ($result[$row['id']] ?? 0) + $row['marks'];
}
var_export($result);

输出:

array (
  0 => 7,
  1 => 14,
  2 => 19,
)

从 PHP7.3 开始,您可以使用 array_key_last() 来简化条件回显。 (Demo)

$result = [];
foreach ($sampleArray as $row) {
    if ($result && !isset($result[$row['id']])) {  // $result is not empty and current id is not yet in output array
        $lastKey = array_key_last($result);
        echo "Sum of ID $lastKey is {$result[$lastKey]}<br><br>";
    }
    echo "id: {$row['id']}, marks: {$row['marks']}<br>";
    $result[$row['id']] = ($result[$row['id']] ?? 0) + $row['marks'];
}
if ($result) {
    echo "Sum of ID {$row['id']} is {$result[$row['id']]}";
}

输出:

id: 0.1, marks: 2
id: 0.2, marks: 4
id: 0.3, marks: 1
Sum of ID 0 is 7

id: 1.1, marks: 6
id: 1.2, marks: 0
id: 1.8, marks: 8
Sum of ID 1 is 14

id: 2.1, marks: 7
id: 2.2, marks: 12
Sum of ID 2 is 19
<?php
$txt = "PHP";
$sampleArray = array(
  array("id"=>0.1, "marks"=>2),
  array("id"=>0.2, "marks"=>4),
  array("id"=>0.3, "marks"=>1),
  array("id"=>1.1, "marks"=>6),
  array("id"=>1.2, "marks"=>0),
  array("id"=>1.3, "marks"=>8),
  array("id"=>2.1, "marks"=>7),
  array("id"=>2.2, "marks"=>12),
);

$total = 0;
$index = 0;
foreach($sampleArray as $item) {
    if($index == 0) { (int)$item['id']; }
    if((int)$item['id'] != $index){
        echo "<b>ID {$index} = {$total} mks</b></br>";
        $index = (int)$item['id'];
        $total = 0;
    }
    echo "ID {$item['id']} = {$item['marks']} mks</br>";
    $total += $item['marks']; 
}
echo "<b>ID {$index} = {$total} mks</b>";

?>

输出:

ID 0.1 = 2 mks
ID 0.2 = 4 mks
ID 0.3 = 1 mks
ID 0 = 7 mks
ID 1.1 = 6 mks
ID 1.2 = 0 mks
ID 1.3 = 8 mks
ID 1 = 14 mks
ID 2.1 = 7 mks
ID 2.2 = 12 mks
ID 2 = 19 mks