Combine arrays with corresponding keys in PHP
Whats the best way to combine two arrays by matching values in the keys in each array. For example I have the two arrays:
Array
(
[id] => 1
[name] => Apple
[color] => Green
)
(
[id] => 2
[name] => Banana
[color] => Yellow
)
(
[id] => 3
开发者_开发问答 [name] => Tomato
[color] => Red
)
Array
(
[product_id] => 1
[price] => 0.50
[weight] => 50
)
(
[product_id] => 2
[price] => 0.99
[weight] => 80
)
(
[product_id] => 3
[price] => 0.35
[weight] => 40
)
And I want to combine where 'id' = 'product_id' to produce:
Array
(
[id] => 1
[name] => Apple
[color] => Green
[price] => 0.50
[weight] => 50
)
(
[id] => 2
[name] => Banana
[color] => Yellow
[price] => 0.99
[weight] => 80
)
(
[id] => 3
[name] => Tomato
[color] => Red
[price] => 0.35
[weight] => 40
)
You would need to write a custom function to do this. For example:
<?php
function combine_arrays($array1,$array2){
$merged_array = array();
for($i=0; $i<count($array1); $i++)
{
if($array1[$i]['id'] == $array2[$i]['product_id'])
{
$merged_array[] = array_merge($array1[$i],$array2[$i]);
}
}
return $merged_array;
}
?>
So, in this case is would create two new arrays by adding the id as index, like this:
$newArray1 = array();
$newArray2 = array();
foreach ($array1 as $key => $value) { $newArray1[$value['id']] = $value; }
foreach ($array2 as $key => $value) { $newArray2[$value['product_id']] = $value; }
After this its easy to merge the arrays:
foreach ($array1 as $key => $value)
{
if (is_array($array1[$key]) && is_array($array2[$key]))
{
$result[] = array_merge($array1[$key], $array2[$key]);
}
}
(You may have to add additional checks if the two arrays do not contain the same id pool or the amount of entires differs)
精彩评论