合并具有通用ID的多维数组 [英] Merge multi-dimensional arrays with common id
问题描述
我有两个多维数组:
第一个数组Pizza:
First array Pizzas:
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没有匹配的配料数组(配料未知),因此对于此Pizza,我想将配料设为 null
并获取下一个数组:
I want to merge these two arrays linking them by pizza_id
. One of the Pizza Ids has no matching array for ingredients (the ingredients are unknown) so for this Pizza I want to set ingredients to null
and get the next array:
新数组PizzaAndIngredients:
New array 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
等,但无法获取数组。另一种方法是建立一个新的查询以及左连接的比萨饼和配料,但是在现实生活中,数组要复杂得多,这意味着要复制大量代码。
I have been fiddling around with array_merge
, foreach
, etc but can not get the array. The alternative is to build a new query and left-join pizzas and ingredients but in real life the arrays are much more complicated and this would mean duplicating a lot of code.
我希望能有一个更有效的解决方案,将两个多维数组合并。
I was hoping for a more efficient solution of merging the two multi-dimensional array's.
我最后一次尝试是:
$PizzaAndIngredients = array();
foreach ($pizzas as $key => $values) {
$PizzaAndIngredients[$key] = array_merge($ingredients, $values);
}
推荐答案
从查询结果中,可以将数组键设置为等于 pizza_id
,或通过 pizza_id
重新索引它们: / p>
When you fetch the rows from the query results you can set the array keys equal to the pizza_id
, or re-index them by the pizza_id
:
$pizza = array_column($pizza, null, 'pizza_id');
$ingredients = array_column($ingredients, null, 'pizza_id');
然后只需创建默认数组 null
如果 $ ingredients
不存在,然后将 $ ingredients
值与 $ pizza
值:
Then just create a default array of null
s to use if the $ingredients
don't exist and then merge $ingredients
values with the $pizza
values:
//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);
}
这篇关于合并具有通用ID的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!