2015-10-05 69 views
3

我有兩個數組作爲跟隨如何使用兩個陣列來獲得結果

[1]=>Array(
    [ingrediant]=>Array(
     [A]=>Chicken [C]=>TomatoJuice 
     ) 
    [price]=> 100 
    ) 
[2]=>Array(
    [ingrediant]=>Array(
     [A]=>Pork [C]=>LimeJuice 
     ) 
    [price]=> 50 
    ) 
[3]=>Array(
    [ingrediant]=>Array(
     [B]=>Chille [C]=>TomatoJuice 
    ) 
    [price]=>100 

    ) 
) 

而且

Array([A]=>Array([name]=>meat [code]=>001) 
     [B]=>Array([name]=>Vegetable [code]=>002) 
     [C]=>Array([name]=>Juice [code]=>003) 
) 

第一陣列顯示的成分 的食物組合和第二個數組顯示類型使用foreach循環例如,

雞+番茄汁組合

雞肉和番茄汁是果汁。 我想通過果汁得到結果。

>Tomatojuice 
-Meat:Chicken, price:100 
-Vegetable:Chille, price:100 
>LimeJuice 
-Meat:Pork, price:100 

我如何使用PHP的foreach得到這些結果。我已經嘗試過幾次了,完全沒有問題。

+1

你能使用SQL得到你想要的實際效果? – user1032531

+0

我已經嘗試了幾次,我真的無法得到的方式。我可以得到所有的組合,但不知道如何分類。 – user3789191

+0

它們完全是兩個數組!!!!這就是爲什麼我無法得到 – user3789191

回答

0

此代碼應解決您的問題

根據您的數組聲明:

$food_combo[] = array(
    'ingrediant'=> array(
     'A' => 'Chicken', 
     'C' => 'TomatoJuice' 
     ), 
    'price'=>100 
); 
$food_combo[] = array(
    'ingrediant'=> array(
     'A' => 'Pork', 
     'C' => 'LimeJuice' 
     ), 
    'price'=>50 
); 
$food_combo[] = array(
    'ingrediant'=> array(
     'B' => 'Chille', 
     'C' => 'TomatoJuice' 
     ), 
    'price'=>100 
); 
$types['A'] = array('name'=>'meat','code'=>'001'); 
$types['B'] = array('name'=>'vegetable','code'=>'002'); 
$types['C'] = array('name'=>'juice','code'=>'003'); 

這裏的算法:

$group_by = 'C'; 
$combo = $output = array(); 

foreach($food_combo as $food){ 

    //array("A","B"....); 
    $missed = array_diff(
     array_keys($food['ingrediant']), 
     isset($combo[$food['ingrediant'][$group_by]]) ? 
      $combo[$food['ingrediant'][$group_by]] : array() 
    ); 

    if(count($missed)){ 
     //remove initial group define as key 
     foreach(array_diff($missed,array($group_by)) as $type_code) 
     $output[$food['ingrediant'][$group_by]][] = 
      $types[$type_code]['name'] . 
      ':' . $food['ingrediant'][$type_code] . 
      ',' . 'price:' . $food['price']; 
    } 
} 
print_r($output);