How can I sum up values from a json string? - php

I get the following json data from a database:
[{"type":"Sig","value":"0.0"},{"type":"SH","value":"9.95"},{"type":"COD","value":"6.95"}][{"type":"Sig","value":"0.0"},{"type":"SH","value":"9.95"},{"type":"COD","value":"6.95"}][{"type":"Sig","value":"0.0"},{"type":"SH","value":"9.95"},{"type":"COD","value":"6.95"}][{"type":"Sig","value":"0.0"},{"type":"SH","value":"9.95"},{"type":"COD","value":"6.95"}]
I'm trying to add all value values together, so: 9.95 + 6.95 ... so that I get 67.6 as result.
I tried the below code, but I am getting 16.9 as repeated values.
for ($i = 0; $i <= $count - 1 ; $i++) {
$charge = $service[$i]['charge'];
$serviceValue = json_decode($charge, true);
$totalservice = 0;
foreach ($serviceValue as $key => $value) {
$totalservice += $value['service_value'];
}
echo $totalservice;
}

You can do it like below:-
$jsonObj = json_decode($json); // Decode the JSON to OBJ
// Now loop and find the SUM
$total = 0;
foreach ($jsonObj as $item){
$total =+ $item->value;
}
// Print the SUM
echo "Sum : $total";
Note:- In your code $totalservice beome 0 every time when loop goes to next iteration and that's why you are getting same value repeated time. So do like (what #u_mulder said) :-
$totalservice = 0;
for ($i = 0; $i <= $count-1 ; $i++) {
.....//rest code
}

I have made the below changes. It works fine.
$totalservice = 0;
for ($i = 0; $i <= $count-1 ; $i++) {
$charge = $service[$i]['charge'];
$serviceValue = json_decode($charge, true);
foreach ($serviceValue as $key => $value) {
$totalservice+= $value['service_value'];
}
echo $totalservice;
}
Thanks for the help

Related

Sum of array in php, array generated from excel file

I am reading excel file in php. I want to show the total of one column in the last row. To do that I need to get the total sum of below array.
part of code to get the below array is,
Array ( [0] => 1 ) Array ( [0] => 2 )
$file = "$filename";
$sheet = (isset($_POST['sheet'])) ? $_POST['sheet'] : '';
$connection = new Spreadsheet_Excel_Reader();
$connection->read($file);
echo"<table>";
$x = 1;
while ($x <= $connection->sheets[$sheet]['numRows']) {
echo "\t<tr>\n";
$y=1;
while ($y <= $connection->sheets[$sheet]['numCols']) {
$cell = isset($connection->sheets[$sheet]['cells'][$x][$y]) ? $connection->sheets[$sheet]['cells'][$x][$y] : '';
echo "\t\t<td>$cell</td>\n";
$y++;
}
echo "\t</tr>\n";
$x++;
}
$x = 2;
while ($x <= $connection->sheets[$sheet]['numRows']) {
$ctnqty = isset($connection->sheets[$sheet]['cells'][$x][16]) ?
$connection->sheets[$sheet]['cells'][$x][16] : '';
$ctnqtyttl = explode(",",$ctnqty);
print_r ($ctnqtyttl);
$x++;
}
I'm suing below code to get the sum of above array, but its giving me the result of 2 only. Please help me here to get the sum 3.
$sum = 0;
foreach ($ctnqtyttl as $value) {
echo $sum = $sum + $value;
}
$ctnqtyttl is overwritten each time with a new value in your second while loop, so it forgets any previous values. The sum you calculate will only be based on the last value it has.
Skip the final foreach loop, and calculate the sum during the second while loop as follows:
$sum = 0; // <-------
$x = 2;
while ($x <= $connection->sheets[$sheet]['numRows']) {
$ctnqty = isset($connection->sheets[$sheet]['cells'][$x][16]) ?
$connection->sheets[$sheet]['cells'][$x][16] : '';
$ctnqtyttl = explode(",", $ctnqty);
print_r ($ctnqtyttl);
$sum += array_sum($ctnqtyttl); // <-------
$x++;
}

Get first value of array and store in new array php

I am trying to make card game.
I have 6 variable that are stored in array. Than I use fisherYates method to randomize array, and display four of them.
Problem is, when I randomize it this way only, it will give only random output of those six, with all different types.
So I want that some repeats like, if you draw four cards, you get output of
ex: club, club, diamond,heart, or heart, star,star,heart.. if you get a point..
I thought to do it like this way: put the array in loop of 4 times, and every time it loops, it stores first, or last value in new array, so that way, I can have greater chances of combination of same cards in output array.
But I'm stuck, and I don't know how to do it :/
this is what I've tried so far
$diamond = 'cube.jpg';
$heart = 'heart.jpg';
$spade = 'spade.jpg';
$club = 'tref.jpg';
$star='star.jpg';
$qmark='qmark.jpg';
$time=microtime(35);
$arr=[$diamond,$heart,$spade,$club,$star,$qmark];
function fisherYatesShuffle(&$items, $time)
{
for ($i = count($items) - 1; $i > 0; $i--)
{
$j = #mt_rand(0, $i);
$tmp = $items[$i];
$items[$i] = $items[$j];
$items[$j] = $tmp;
}
return $items;
}
$i=0;
do {
$niz[$i]=fisherYatesShuffle($arr,$time);
reset($niz);
$i++;
} while ($i <= 3);
Got a solution. Was just to simply do foreach of first element of multidimensional array :)
Code goes like this:
$diamond = 'cube.jpg';
$heart = 'heart.jpg';
$spade = 'spade.jpg';
$club = 'tref.jpg';
$star='star.jpg';
$qmark='qmark.jpg';
$time=microtime(35);
$arr=[$diamond,$heart,$spade,$club,$star,$qmark];
$niz=array();
$i=0;
do {
$niz[$i]=fisherYatesShuffle($arr,$time);
//reset($niz);
$i++;
} while ($i <= 3);
foreach ($niz as $key ) {
$randomArr[]=$key[0]; ;
}
function fisherYatesShuffle(&$items, $time)
{
for ($i = count($items) - 1; $i > 0; $i--)
{
$j = #mt_rand(0, $i);
$tmp = $items[$i];
$items[$i] = $items[$j];
$items[$j] = $tmp;
}
return $items;
}
print_r($randomArr);

for loop -- ununderstandable behavior

I have have these for loops:
for ($x = 0; $x<2;$x++){
$allproducts = array();
for ($y = 0; $y<105;$y++) { //<<<<<<<<<<<<< this (105) is the number I mean
$allproducts[] = 'test'.$y;
}
echo "<pre>";
echo "allproducts 0 -- ";
var_dump($allproducts);
echo "</pre>";
for ($i = 0; $i < count($allproducts); $i++) {
$result = array_slice($allproducts, 0, 20);
echo "<pre>";
echo "result -- ";
var_dump($result);
echo "</pre>";
$allproducts = (array_diff($allproducts, $result));
echo "<pre>";
echo "allproducts 1 -- ";
var_dump($allproducts);
echo "</pre>";
}}
In real code (here:)
for ($x = 0; $x<1;){
$allproducts = array();
$abfrage = "SELECT sku FROM skulist";
if ($result = $sql->query($abfrage))
{
while ($row = $result->fetch_assoc()) {
$allproducts[] = $row['sku'];
}
}
for ($i = 0; $i < count($allproducts); ++$i) {
$result = array_slice($allproducts, 0, 20);
$allproducts = (array_diff($allproducts, $result));
//.... more code
}}
...I take data from DB instead of this for loop:
$allproducts = array();
for ($y = 0; $y<105;$y++) { //<<<<<<<<<<<<< this (105) is the number I mean
$allproducts[] = 'test'.$y;
}
but changed it to show/ for easier reconstruction.
The behavior is the same:
When I have 105 entries in my array, I don't get an empty array output for
echo "allproducts 1 -- ";
var_dump($allproducts);
which is the desired behavior.
When I change 105 to (eg.) 65, it outputs an empty arrays
allproducts 1 -- array(0)
at the end of the second nested loop:
for ($i = 0; $i < count($allproducts); $i++) {
Now I have three problems:
why does this happen? I don't get the difference
how can I achieve, that there is no empty array at the end? (stops my programs work)
I need 20 values in every $result array
for ($i = 0; $i < count($allproducts); $i++) {
// ...
$allproducts = (array_diff($allproducts, $result));
You are changing your $allproducts array while going through it! How can you expect it to work reliably then?
Instead, try:
foreach( $allproducts as $i => $product)
Although I must admit I'm not sure what you're trying to do.

Find specific value array multidimensional php

I'm new on PHP and I want to find the 0 and replace with the number that is missed, inside the inner array, on a multidimensional array. If the inner array has more than two 0's, it will be ignored and goes to the next.
$list = array("First"=>array(0,1,2,3,0,5,6,7,8,9),
"Second"=>array(0,1,2,3,4,5,6,7,8,9),
"Third"=>array(0,1,2,3,4,5,0,0,8,9),
"Fourth"=>array(0,1,2,3,4,5,6,7,8,0),
"Fifth"=>array(0,1,2,3,4,5,0,7,8,9),
"Sixth"=>array(0,0,0,3,4,5,6,0,0,0),
"Seventh"=>array(0,1,2,3,0,0,6,7,8,9),
"Eighth"=>array(0,1,2,3,4,5,0,7,8,9),
"Ninth"=>array(0,1,2,3,4,0,6,7,8,9),
"Tenth"=>array(0,0,2,3,4,5,6,7,8,9));
$countZero = 0;
foreach($list as $lvl) {
foreach($lvl as $ind => $val) {
if($countZero = array_count_values($lvl[$val] === 0))
$list[$ind][$val] = 45 - array_sum($ind);
echo $count;
}
}
I want all inner arrays, that have two 0's get only one, to have all numbers in sequence i.e.
"First"=>array(0,1,2,3,4,5,6,7,8,9);
Please, help me.
I tried this code below, trying to finde the 0's.
$counts = 0;
$newArr = array();
foreach($list as $lvl) {
if(is_array($lvl)) {
for($i = 0; $i < count($lvl) - 1; $i++) {
if(($lvl[$i] == 0) < 2){
$counts++;
$newArr[$i] = 45 - array_sum($lvl);
}
}
}
}
print_r($newArr);
This is a solution using array_walk:
array_walk($list,
function(&$numbers) {
$zeroIndex = 0;
foreach($numbers as $i => $number) {
if( $number === 0 ) {
if( $zeroIndex > 0 ) {
return;
}
$zeroIndex = $i;
}
}
$numbers[$zeroIndex] = $zeroIndex;
});
You don't need to count all the zeros. You just need to check if there are less than 3 zeros.
I'm saving the index (position) of zero ($zeroIndex = $i).
I'm assuming that the first number is always a zero ($zeroIndex = 0).
The index of the second zero is greater than zero. If I find a zero when the index of the last found zero is greater than zero (if( $zeroIndex > 0 )), this means that there are more than two zeros.
In fact,here is what I've done and worked.
$list = array(array(1,2,3,0,5,6,7,8,9),
array(1,2,3,4,5,6,7,8,9),
array(1,2,3,4,5,0,0,8,9),
array(1,2,3,4,5,6,7,8,0),
array(1,2,3,4,5,0,7,8,9),
array(0,0,3,4,5,6,0,0,0),
array(1,2,3,0,0,6,7,8,9),
array(1,2,3,4,5,0,7,8,9),
array(1,2,3,4,0,6,7,8,9));
for($l = 0; $l < count($list); $l++)
{
$total = 0;
$countZ = 0;
for($i=0; $i < 9; $i++)
{
if($list[$l][$i] == 0)
{
$countZ++;
$indexZero = $i;
}
$total += $list[$l][$i];
if($countZ > 1) {
break;
}
}
$list[$l][$indexZero] = 45 - $total;
}
print_r($list);
TY all.

$_GET form variables in a loop

I've got a form with input names like price1, price2, price3 and I'm trying to get these values in another page. I'm sending it using GET.
for ($i = 1; $i < $qtd_itens; $i++) {
$price = $_GET['price" + $i + "'];
echo $price;
}
How should I declare the $price variable?
Need to put . in place of + sign...
for ($i = 1; $i < $qtd_itens; $i++) {
$price = $_GET['price'. $i. ''];
echo $price;
}
If you just want to collect all the prices you can do:
$prices = array();
for ($i = 1; $i < $qtd_itens; $i++) {
$prices[] = $_GET["price" . $i];
}
var_dump($prices);
To clarify:
$arr[] = "a";
is shorthand for:
array_push($arr, "a");
or
$arr[$i] = "a";
If you form input having price1, price2, price3... etc, you simply make this for view content of data send:
print_r($_REQUEST)
This show you data in array send, and collect with foreach with this:
$prices = array();
foreach ($_REQUEST as $key=>$val) {
$prices[$key] = $val;
}
print_r($prices);

Categories