Last active
April 26, 2020 21:12
-
-
Save pacmanito/634876940678c174501fd8ebbb04936d to your computer and use it in GitHub Desktop.
Calculate sold goods in multi-dimensional array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
echo "\n" . '-=-=-=-=-=BEFORE LOOP-=-=-=-=-=-=' . "\n". "\n"; | |
$a = array('product name' => 'gasoline', 'quantity' => 2); | |
$b = array('product name' => 'oil', 'quantity' => 3); | |
$order1 = array($a,$b); | |
$c = array('product name' => 'bottle', 'quantity' => 2); | |
$d = array('product name' => 'gasoline', 'quantity' => 3); | |
$e = array('product name' => 'lighter', 'quantity' => 1); | |
$order2 = array($c,$d,$e); | |
$f = array('quantity' => 13, 'product name' => 'mask'); | |
$g = array('product name' => 'oil', 'quantity' => 7); | |
$h = array('quantity' => 2, 'product name' => 'lighter', ); | |
$order3 = array($f,$g,$h); | |
$orders = array ($order1,$order2,$order3); | |
print_r($orders); | |
$single_order_array=array(); | |
$results=array(); | |
echo "\n" . '-=-=-=-=-=LOOP-=-=-=-=-=-=' . "\n". "\n"; | |
foreach ($orders as $key => $order) { | |
$single_order_array = (array_column($order, 'quantity', 'product name')); | |
print_r($single_order_array); | |
foreach ($single_order_array as $product=>$quantity){ | |
if (array_key_exists($product, $results)){ | |
$results[$product]+=$quantity;} | |
else {$results += array ($product=>$quantity); | |
} | |
} | |
echo "\n" . '<<<<BREAK>>>>' . "\n". "\n"; | |
} | |
echo "\n" . '-=-=-=-=-=AFTER LOOP-=-=-=-=-=-=' . "\n". "\n"; | |
print_r($results); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment