gpt4 book ai didi

PHP - 合并两个值匹配的关联数组

转载 作者:行者123 更新时间:2023-12-04 00:04:50 25 4
gpt4 key购买 nike

我有两个需要合并的数组。我可以遍历每个数组并手动合并。但是,是否有内置函数来执行此操作?

数组 1:

Array
(
[0] => Array
(
[detail_image_id] => 6389
[product_name] => Starter broadband Package
)

[1] => Array
(
[detail_image_id] => 6358
[product_name] => Starter broadband Package
)
)

数组 2:
Array
(
[0] => Array
(
[detail_image_id] => 6358
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg
)

[1] => Array
(
[detail_image_id] => 6389
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg
)
)

预期输出数组是:
Array
(
[0] => Array
(
[detail_image_id] => 6389
[product_name] => Starter broadband Package
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg
)

[1] => Array
(
[detail_image_id] => 6358
[product_name] => Starter broadband Package
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg
)
)

我只从数组中添加了一个样本。数组很大。有没有像 array_merge() 这样的 PHP 函数或 array_map()我们可以使用代替手动循环和迭代器吗?

最佳答案

更老更聪明:我从几年前就删除了我的答案,因为我不再推荐这些技术。合并数组,将它们提供给 foreach() 将是最简洁和有效的。循环,然后“联合”(+ 用作数组联合运算符)相关行中的数据。
空合并运算符( ?? )用于确保总有一些东西可以“联合”。
代码:( Demo )

$result = [];
foreach (array_merge($array1, $array2) as $row) {
$result[$row['detail_image_id']] = ($result[$row['detail_image_id']] ?? []) + $row;
}

var_export(array_values($result));
输出:
array (
0 =>
array (
'detail_image_id' => '6389',
'product_name' => 'Starter broadband Package',
'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg',
),
1 =>
array (
'detail_image_id' => '6358',
'product_name' => 'Starter broadband Package',
'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg',
),
)

关于PHP - 合并两个值匹配的关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50384669/

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