PHP如何使用数组数组合并一个对象数组

时间:2011-09-23 00:27:37

标签: php arrays object

首先,对于长篇解释感到抱歉。我在PHP中有两个数组。第一个数组是一个对象数组。第二个数组是一个数组数组。基本上,我想循环,并将对象与其匹配的数组合并,并返回一个合并的对象。

请参阅对象数组结构的以下print_r()

Array
(
[0] => stdClass Object
    (
        [gear] => helloworld
        [status] => running
        [started] => 40 Minutes Ago
        [start] => index.js
        [route] => 127.0.0.1:3000
        [parameters] => Array
            (
            )

    )

[1] => stdClass Object
    (
        [gear] => test
        [status] => stopped
        [started] => 
        [start] => index.js
        [route] => 
        [parameters] => Array
            (
            )

    )

[2] => stdClass Object
    (
        [gear] => test2
        [status] => stopped
        [started] => 
        [start] => index.js
        [route] => 
        [parameters] => Array
            (
                [0] => first
                [1] => second
                [2] => third
            )

    )

)

请参阅以下数组结构数组的print_r()

Array
(
[0] => Array
    (
        [gear] => helloworld
        [machine_id] => E6z5ekvQ
        [created_by] => 10010
        [modified_by] => 10010
        [created] => 2011-09-22T16:30:11-07:00
        [modified] => 2011-09-22T16:30:11-07:00
    )

[1] => Array
    (
        [gear] => test
        [machine_id] => E6z5ekvQ
        [created_by] => 10010
        [modified_by] => 10010
        [created] => 2011-09-22T16:44:25-07:00
        [modified] => 2011-09-22T16:44:25-07:00
    )

[2] => Array
    (
        [gear] => test2
        [machine_id] => E6z5ekvQ
        [created_by] => 10010
        [modified_by] => 10010
        [created] => 2011-09-22T16:45:43-07:00
        [modified] => 2011-09-22T16:45:43-07:00
    )

)

所以基本上两者的匹配键都是gear。所以我们应该匹配第一个对象的齿轮和阵列中的第二个齿轮,并返回类似的东西:

stdClass Object
    (
        [gear] => helloworld
        [status] => running
        [started] => 40 Minutes Ago
        [start] => index.js
        [route] => 127.0.0.1:3000
        [parameters] => Array
            (
            )
        [machine_id] => E6z5ekvQ
        [created_by] => 10010
        [modified_by] => 10010
        [created] => 2011-09-22T16:30:11-07:00
        [modified] => 2011-09-22T16:30:11-07:00
    )

注意,齿轮合并到物体的一个属性中,显然齿轮不会出现两次。想法?

1 个答案:

答案 0 :(得分:3)

如果您可以按gear或某个唯一值对数组建立索引,则会更容易。

$indexed = array();

// create an array using 'gear' as the index
foreach($arrayValue as $value) {
    $indexed[$value['gear']] = $value;
}

// loop over each object
foreach($objectArray as $obj) {
    $value = $indexed[$obj->gear]; // find the corresponding array
    foreach($value as $name => $val) {
        $obj->$name = $val; // assign each array index/value pair to the object
    }
}

如果可能的话,默认情况下让你的代码返回带索引的数组,你可以删除第一个foreach循环。

希望有所帮助。