I have two associative arrays. I need to subtract ($price - $tax) to get $total price:
$price['lunch'] = array("food" => 10, "beer"=> 6, "wine" => 9);
$price['dinner'] = array("food" => 15, "beer"=> 10, "wine" => 10);
$tax['lunch'] = array("food" => 2, "beer"=> 3, "wine" => 2);
$tax['dinner'] = array("food" => 4, "beer"=> 6, "wine" => 4);
Desired result array:
$result['lunch'] = (['food'] => 8, ['beer'] =>3, ['wine'] => 7 )
$result['dinner'] = (['food'] => 11, ['beer'] =>4, ['wine'] => 6 )
I'm trying following function and array_map to no avail:
function minus($a, $b) {
return $a - $b;
}
foreach ($price as $value)
{
$big = $value;
foreach($tax as $v) {
$small = $v;
$e[] = array_map("minus",$big, $small);
}
}
With above i get four arrays (first and last one is correct though) so it's not correct. Thanks for any info!
You could compare using keys instead of array mapping. With a double foreach, you can do any number of meals and food types:
foreach(array_keys($price) as $meal)
{
foreach(array_keys($price[$meal]) as $type)
{
$e[$meal][$type] = $price[$meal][$type] - $tax[$meal][$type];
}
}
Note, this code doesn't look out for missing items in either the meals or the food types...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With