我有两个数组如下
[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)
)
First Array显示食物组合和第二阵列显示的成分类型 例如,
Chicken + tomatojuice Combo
鸡肉是肉,番茄汁是果汁。 我想通过果汁获得结果如下。
>Tomatojuice
-Meat:Chicken, price:100
-Vegetable:Chille, price:100
>LimeJuice
-Meat:Pork, price:100
如何使用php foreach获得这些结果。我已经尝试了好几次。不管怎么样。
答案 0 :(得分: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);