我有两个多维数组:
第一阵比萨:
0 => array:2 [▼
"pizza_id" => 11
"pizza_name" => "Hawaï"
]
1 => array:2 [▼
"pizza_id" => 12
"pizza_name" => "Tonno"
]
2 => array:2 [▼
"pizza_id" => 13
"pizza_name" => "Surprise"
]
第二阵列成分:
0 => array:4 [▼
"pizza_id" => 11
"ingredient_one" => "Ananas"
"ingredient_two" => "Onion"
"ingredient_three" => "Ham"
]
1 => array:4 [▼
"pizza_id" => 12
"ingredient_one" => "Tuna"
"ingredient_two" => "Onion"
"ingredient_three" => null
]
我想合并这两个通过pizza_id
链接它们的数组。其中一个Pizza Ids没有匹配的成分阵列(成分未知)所以对于这个披萨,我想将成分设置为null
并获得下一个阵列:
新阵列PizzaAndIngredients:
0 => array:5 [▼
"pizza_cid" => 11
"pizza_name" => "Hawaï"
"ingredient_one" => "Ananas"
"ingredient_two" => "Onion"
"ingredient_three" => "Ham"
]
1 => array:5 [▼
"pizza_id" => 12
"pizza_name" => "Tonno"
"ingredient_one" => "Tuna"
"ingredient_two" => "Onion"
"ingredient_three" => null
]
2 => array:5 [▼
"pizza_id" => 13
"pizza_name" => "Surprise"
"ingredient_one" => null
"ingredient_two" => null
"ingredient_three" => null
]
我一直在摆弄array_merge
,foreach
等,但无法获得数组。另一种方法是构建一个新的查询和左连接比萨饼和成分,但在现实生活中,数组要复杂得多,这意味着要复制大量代码。
我希望能够更有效地合并两个多维阵列的解决方案。
我的最后一次尝试是:
$PizzaAndIngredients = array();
foreach ($pizzas as $key => $values) {
$PizzaAndIngredients[$key] = array_merge($ingredients, $values);
}
答案 0 :(得分:2)
从查询结果中获取行时,您可以将数组键设置为pizza_id
,或者按pizza_id
重新索引它们:
$pizza = array_column($pizza, null, 'pizza_id');
$ingredients = array_column($ingredients, null, 'pizza_id');
然后创建一个null
的默认数组,以便在$ingredients
不存在时使用,然后将$ingredients
值与$pizza
值合并:< / p>
//get an ingredient array
$temp = reset($ingredients);
//combine keys and an array of nulls
$default = array_combine(array_keys($temp),
array_fill(0, count($temp), null));
foreach($pizza as $id => $p_values) {
//check if $ingredients[$id] exists, if not use the default
$i_values = isset($ingredients[$id]) ? $ingredients[$id] : $default;
//you can also use just $result[] if you don't need the pizza_id as key
$result[$id] = array_merge($i_values, $p_values);
}