2011-10-01 199 views
3

我有兩個關聯數組。我需要減去($價格 - $含稅),以獲得$總價: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['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); 
     }  
     } 

上面我得到了四個數組(第一個也是最後一個是正確的),所以它是不正確的。感謝您的任何信息!

回答

4

您可以使用鍵而不是數組映射進行比較。有了雙重的foreach,你可以做任何數量的膳食和食物類型:

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

注意,這個代碼不看出來無論是在進餐或食物種類物品丟失......

+0

哈哈,你比我快:D我投你一票。 – ariefbayu

+0

第二個foreach中的$用餐是一個字符串不是數組 - 我得到錯誤 - 仍然我不知道這應該如何工作。 – phpJs

+0

對不起,我的錯誤 –

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 
     ) 

)