php subtract associative arrays
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,开发者_Go百科 "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 the structure of $price
and $tax
are always equals, you can use the following code:
<?php
$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);
$result = array();
foreach( $price as $what => $value)
{
foreach( $value as $food => $foodPrice )
{
$result[$what][$food] = $foodPrice - $tax[$what][$food];
}
}
Result:
print_r($result);
Array
(
[lunch] => Array
(
[food] => 8
[beer] => 3
[wine] => 7
)
[dinner] => Array
(
[food] => 11
[beer] => 4
[wine] => 6
)
)
精彩评论