php减去关联数组

时间:2011-10-01 00:11:15

标签: php multidimensional-array

我有两个关联数组。我需要减去($ price - $ tax)以获得$ total总价:

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

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

2 个答案:

答案 0 :(得分:4)

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

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

请注意,此代码不会注意膳食或食物类型中缺少的物品......

答案 1 :(得分:1)

如果$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
        )

)