PHP - 使用键/ id合并2个对象数组

时间:2015-03-06 18:07:21

标签: php arrays merge array-merge

我想根据Array1的'id'字段和Array2的'itemVendorCode'合并2个对象数组。我还想从结果数组中删除任何不匹配的内容。

数组1:

Array
(
    [0] => stdClass Object
        (
            [id] => 10-423-1176
            [qty] => 2
            [price] => 12.6
        )

    [1] => stdClass Object
        (
            [id] => 89-575-2354
            [qty] => 24
            [price] => 230.35
        )

    [2] => stdClass Object
        (
            [id] => 89-605-1250
            [qty] => 2
            [price] => 230.35
        )
  )

ARRAY2:

Array
(
    [0] => Item Object
        (
            [internalId] => 14062
            [itemVendorCode] => 89-605-1250
        )

    [1] => Item Object
        (
            [internalId] => 33806
            [itemVendorCode] => 89-575-2354
        )

    [2] => Item Object
        (
            [internalId] => 64126
            [itemVendorCode] => 26-295-1006
        )
)

2 个答案:

答案 0 :(得分:1)

我能够通过以下代码解决这个问题:

$indexed = array();

foreach($itemsArray as $value) {
    $indexed[$value->itemVendorCode] = $value;
}


$results = array();

foreach($vendorItems as $obj) {
    $value = $indexed[$obj->id];

    if (isset($value)) {
        foreach($value as $name => $val) {
            $obj->$name = $val; 
            array_push($results, $obj);
        }
    }

}

print_r($results);

归功于原始海报。我刚修改了一下,

我能够得到这样的结果:

Array
(
    [0] => stdClass Object
        (
            [id] => 10-423-1176
            [qty] => 2
            [price] => 12.6
            [internalId] => 2035
            [itemVendorCode] => 10-423-1176
        )

    [1] => stdClass Object
        (
            [id] => 10-423-1176
            [qty] => 2
            [price] => 12.6
            [internalId] => 2035
            [itemVendorCode] => 10-423-1176
        )

    [2] => stdClass Object
        (
            [id] => 14-102-1010
            [qty] => 16
            [price] => 3.2
            [internalId] => 57033
            [itemVendorCode] => 14-102-1010
        )
)

答案 1 :(得分:0)

我认为你必须使用array_map函数,它为你提供了一个在数组上执行的回调函数。

在回调函数中: - 声明你的array1 - foreach第二个数组      - 设置一个if语句来检查id值的当前迭代是否与array2的itemVendorCode匹配并返回

类似的东西:

// You have to specify to PHP to use a local copy of your $array2 to works with it into your callback
$cb = function ($obj1) use ($array2)
{
    // you foreach this array
    foreach ($array2 as $obj2) {
        // if the value of id matches itemVendorCode
        if ($obj1->id === $obj2->itemVendorCode) {
            // you return the id
            return $obj->id;
        }
    }
};

// this function will fill a new array with all returned data
$mergedArray = array_map($cb, $array1);

此代码是一个示例,但是没有为您提供针对您的解决方案,请尝试更新它以执行您想要的操作;)