将两个数组合并到一个蛋糕php中
问题描述:
This is the array i have.
Array
(
[0] => Array
(
[FoodItem] => Array
(
[id] => B102
[food_item_title] => Prown cocktail
[active] => 1
)
[MenuFoodItem] => Array
(
[menu_id] => 2
)
)
)
I want to combine FoodItem and MenuFoodItem array into one as following using native php or cake php
Array
(
[0] => Array
(
[FoodItem] => Array
(
[id] => B102
[food_item_title] => Prown cocktail
[active] => 1
[menu_id] => 2
)
)
)
答
You can do this using blow code.
$i = 0;
foreach($datas as $data)
{
$result[$i]['FoodItem'] = $data['FoodItem'];
$result[$i]['FoodItem']['menu_id'] = $data['MenuFoodItem']['menu_id'];
$i++;
}
答
You can also do like this
$arr is the array to work with
$arr_merged = array();
for($i=0;$i<count($arr);$i++)
{
$arr_merged[$i]['FoodItem'] = array_merge($arr[$i]['FoodItem'], $arr[$i]['MenuFoodItem']);
}
答
Array Operators: $a + $b Union of $a and $b.
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.