多数组合并
我在合并基于 1 个索引的多维数组时遇到了一些困难。我不知道是我绞尽脑汁太久了,把自己搞砸了还是怎么的,但我就是想不明白。
来自 2 个数组的 2 个索引的示例如下:
// Array1:
[0] => Array
(
[appID] => 58510
[name] => SomeRandomApp
[users] => Array
(
[0] => randomUser
)
)
// Array2:
[0] => Array
(
[appID] => 58510
[name] => SomeRandomApp
[users] => Array
(
[0] => anotherUser
)
)
// Desired Result:
[0] => Array
(
[appID] => 58510
[name] => SomeRandomApp
[users] => Array
(
[0] => randomUser
[1] => anotherUser
)
)
我想基于“appID”进行合并,而不是其他。然后对用户进行另一次合并,这样如果另一个索引有不同的用户,它们都会合并。
I'm having a bit of difficulty merging a multi-dimensional array based on 1 index. I don't know if I've just been racking my brain too long and have messed myself up or what, but I can't get this.
An example of 2 indices from 2 arrays is as such:
// Array1:
[0] => Array
(
[appID] => 58510
[name] => SomeRandomApp
[users] => Array
(
[0] => randomUser
)
)
// Array2:
[0] => Array
(
[appID] => 58510
[name] => SomeRandomApp
[users] => Array
(
[0] => anotherUser
)
)
// Desired Result:
[0] => Array
(
[appID] => 58510
[name] => SomeRandomApp
[users] => Array
(
[0] => randomUser
[1] => anotherUser
)
)
I'd like to merge based on "appID" and nothing else. And then do another merge on users so that if another index has different users, they all just merge.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来您想获取每个应用程序的用户列表。我想你必须循环浏览它们。您可以创建一个由 appID 索引的结果数组,如下所示(未测试):
这假设同一用户不会被列出两次。如有必要,您可以修改该函数以处理重复项。
作为旁注,在重复键的情况下, array_merge 将用第二个数组覆盖第一个数组中的值,我不认为这是您想要的行为。
It sounds like you want to get a list of users for each app. I think you will have to loop through them. You could created a result array indexed by the appID like this (not tested):
This assumes the same user won't be listed twice. You can modify the function to handle duplicates if necessary.
As a side note, array_merge will overwrite values in the first array with the second in the case of duplicate keys, which I don't believe is the behaviour you want here.
@Andrew,您是否尝试使用 array_merge_recursive() 来代替?
@Andrew, have you try to use
array_merge_recursive()
instead?终于一切都解决了。
虽然很草率,但它确实有效,而且如果我自己这么说的话,它的效果非常好。还没有对它进行基准测试,但我确实针对相当重的阵列对其进行了测试,没有真正明显的延迟。每个索引中的数据比我显示的要多得多。总而言之,我很满足。
我希望这能帮助别人。
Finally got it all worked out.
It's pretty sloppy, but it works, and it works pretty damn well if I do say so myself. Haven't benchmarked it yet but I did test it against a pretty heavy array with no real noticeable delay. There's a LOT more data in each index than what I'm showing. All in all, I'm content.
I hope this'll help someone else out.