PHP - while loop
print "<ul>"; foreach ($arr as $value) { echo("<li>" . $value[storeid] . " " . ($value[dvdstock] + $value[vhsstock]) . "</li>"); } print "</ul>"; Will output
β’2 20 β’2 10 β’1 20 β’1 20 β’1 10 I was wondering how I will adapt this loop so that it displays the common values ββfor each value & [storeid]
β’1 50 β’2 30 Many thanks:)
Use another array to calculate the desired values:
// setup a quick place to store the data $stores = array(); foreach ($arr as $value) { if(!isset($stores[$value['storeid']])){ // init check required to avoid Notices $stores[$value['storeid']] = $value['dvdstock'] + $value['vhsstock']; }else{ $stores[$value['storeid']] += $value['dvdstock'] + $value['vhsstock']; } } ksort($stores); // sort by storeid ASC print "<ul>"; // loop through the new data foreach ($stores as $id => $value) { echo("<li>" . $id . " " . ($value) . "</li>"); } print "</ul>"; If you are retrieving data from an SQL database, you must do this using the SUM() functions in SQL, as it is more efficient. If the data source is somewhere else, you should do something like this:
//Sum data foreach ($arr as $value) { if (!isset($sums[$value['storeid']])) { // init check required to avoid Notices $sums[$value['storeid']] = $value['dvdstock'] + $value['vhsstock']; } else { $sums[$value['storeid']] += $value['dvdstock'] + $value['vhsstock']; } } ksort($sums); // sort by storeid ASC print "<ul>"; foreach ($sums as $key => $sum) { echo("<li>$key $sum</li>"); } print "</ul>"; This is a for loop, and you should do two of them. First calculate the sum and then iterate over these values:
$data = array(); foreach ($arr as $value) { if (!isset($data[$value['storeid']])) { // init check required to avoid Notices $data[$value['storeid']] = $value['dvdstock'] + $value['vhsstock']; } else { $data[$value['storeid']] += $value['dvdstock'] + $value['vhsstock']; } } ksort($data); // sort by storeid ASC print "<ul>"; foreach ($data as $storeid => $sum) { echo('<li>' . $storeid . ' ' . ($sum) . '</li>'); } print "</ul>"; Btw one word about lines:
Use single quotation marks ' with concatenation . : 'foo: ' . $bar 'foo: ' . $bar .
Or double quotes " and put the variables inside the string: "foo: $bar" .
The correct version is:
<?php $initial = array ( array ( 'id' => 1, 'amount' => 10 ), array ( 'id' => 1, 'amount' => 10 ), array ( 'id' => 2, 'amount' => 20 ), array ( 'id' => 2, 'amount' => 20 ), array ( 'id' => 2, 'amount' => 20 ), ); $result = array (); foreach ($initial as $value) { $result[$value['id']] += $value['amount']; } print_r($result); ?>