gpt4 book ai didi

PHP 如何将对象数组与数组数组合并

转载 作者:行者123 更新时间:2023-12-04 06:13:23 29 4
gpt4 key购买 nike

首先,抱歉冗长的解释。我在 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
)

请注意,齿轮已合并到对象的一个​​属性中,显然齿轮不会出现两次。想法?

最佳答案

如果您可以通过 gear 索引数组或者一些独特的值(value),它会容易得多。

$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 循环。

希望有帮助。

关于PHP 如何将对象数组与数组数组合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7523017/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com