在 PHP 中将数组与相应的键组合起来
通过匹配每个数组中键中的值来组合两个数组的最佳方法是什么?例如,我有两个数组:
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
)
Whats the best way to combine two arrays by matching values in the keys in each array. For example I have the two 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
)
And I want to combine where 'id' = 'product_id' to produce:
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
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要编写一个自定义函数来执行此操作。例如:
You would need to write a custom function to do this. For example:
因此,在这种情况下,将通过添加 id 作为索引来创建两个新数组,如下所示:
之后,很容易合并数组:(
如果两个数组不包含相同的 id 池,您可能需要添加额外的检查或整体的数量不同)
So, in this case is would create two new arrays by adding the id as index, like this:
After this its easy to merge the arrays:
(You may have to add additional checks if the two arrays do not contain the same id pool or the amount of entires differs)