PHP减去关联数组



我有两个关联数组。我需要减去($price - $tax)来得到$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);

期望结果数组:

 $result['lunch'] = (['food'] => 8, ['beer'] =>3, ['wine'] => 7 )
 $result['dinner'] = (['food'] => 11, ['beer'] =>4, ['wine'] => 6   )

我正在尝试以下函数和array_map无效:

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);
        }       
        }

上面我得到四个数组(第一个和最后一个是正确的),所以它是不正确的。谢谢你的任何信息!

您可以使用键而不是数组映射进行比较。使用双foreach,您可以设置任意数量的膳食和食物类型:

foreach(array_keys($price) as $meal)
{
    foreach(array_keys($price[$meal]) as $type)
    {
        $e[$meal][$type] = $price[$meal][$type] - $tax[$meal][$type];
    }
}

注意,这段代码不会查找餐点或食物类型中缺少的项目…

如果$price$tax的结构总是相等,则可以使用以下代码:

<?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];
    }
}
结果:

print_r($result); 
Array
(
    [lunch] => Array
        (
            [food] => 8
            [beer] => 3
            [wine] => 7
        )
    [dinner] => Array
        (
            [food] => 11
            [beer] => 4
            [wine] => 6
        )
)

相关内容

  • 没有找到相关文章

最新更新