Last active
April 26, 2020 21:11
-
-
Save pacmanito/822766b8e05c1f2330622572a7f59392 to your computer and use it in GitHub Desktop.
Calculate sold goods in multi-dimensional array with recursive function
This file contains hidden or 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 | |
$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); | |
$result = []; | |
$n = 0; | |
function products_sold (array $array) { | |
global $result; | |
global $n; | |
foreach ($array as $key => $value) { | |
if (is_array($value)) { | |
products_sold ($value); | |
} | |
else { | |
echo ++$n . ". " . "I'm inside, darling!" . "\n"; | |
if (!is_string($value)) { | |
$product_name = $array['product name']; | |
if(array_key_exists($product_name, $result)) { | |
$result[$product_name] += $value; | |
} | |
else { | |
$result += [$product_name => $value]; | |
} | |
echo "\n\n";print_r($result);} | |
} | |
} | |
return $result; | |
} | |
$result = products_sold ($orders); | |
echo "\n\n" . "***** FIN ******" . "\n\n"; | |
print_r ($result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment