简体   繁体   English

在PHP中将数组与相应的键组合在一起

[英]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: 我想结合'id'='product_id'来产生:

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: 因此,在这种情况下,将通过添加id作为索引来创建两个新数组,如下所示:

$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) (如果两个数组不包含相同的id池或者entires的数量不同,则可能必须添加其他检查)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM