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

时间:2011-05-22 20:41:57

标签: php 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
)

我想结合哪里' 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
)

2 个答案:

答案 0 :(得分:2)

您需要编写自定义函数才能执行此操作。例如:

<?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;
}
?>

答案 1 :(得分:0)

因此,在这种情况下,将通过添加id作为索引来创建两个新数组,如下所示:

$newArray1 = array();
$newArray2 = array();

foreach ($array1 as $key => $value) { $newArray1[$value['id']] = $value; }
foreach ($array2 as $key => $value) { $newArray2[$value['product_id']] = $value; }

之后很容易合并数组:

foreach ($array1 as $key => $value)
{
    if (is_array($array1[$key]) && is_array($array2[$key]))
    {
        $result[] = array_merge($array1[$key], $array2[$key]);
    }
}

(如果两个数组不包含相同的id池或者entires数量不同,则可能需要添加额外的检查)