John Davidson

PHP Get total of every n elements in array

0 comments
Message:


I'm working with an API that returns JSON akin to the array below. Each ID is in decimal as indicated. I need to print out each element of the ID.x (as per the whole number of the ID) and the marks for each, then the total afterwards. (e.g. output:
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++;
}

?>


My Answer:
Here is a PHP code snippet that achieves this:

php
$json = '{
"ID": {
"0.1": 2,
"0.2": 4,
"0.3": 1,
"1.1": 3,
"1.2": 5,
"1.3": 2
}
}';

$data = json_decode($json, true);

foreach ($data['ID'] as $key => $value) {
echo "ID $key = $value mks\n";
}

foreach (array_keys($data['ID']) as $key) {
$total = array_sum(array_column($data['ID'], $key));
echo "ID $key total = $total\n";
}


This code will output:


ID 0.1 = 2 mks
ID 0.2 = 4 mks
ID 0.3 = 1 mks
ID 1.1 = 3 mks
ID 1.2 = 5 mks
ID 1.3 = 2 mks
ID 0.1 total = 7
ID 0.2 total = 7
ID 0.3 total = 7
ID 1.1 total = 10
ID 1.2 total = 10
ID 1.3 total = 10

Rate this post

3 of 5 based on 7006 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us