Multi array_merge
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.
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):
function app_users($array1, $array2) {
$combined = array ();
foreach (array($array1, $array2) as $arr) {
foreach ($arr as $values) {
if (!isset($combined[$values['appId']])) {
$combined[$values['appID']] = $values;
}
else {
$combined[$values['appID']]['users'][] = $values['users'][0];
}
}
}
}
$result = app_users($array1, $array2);
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, have you try to use array_merge_recursive()
instead?
Finally got it all worked out.
$newArray = array();
foreach($data as $item)
{
$appID = $item['appID'];
$users = $item['users'];
unset($item['users']);
unset($item['hoursOnRecord']);
if(!isset($newArray[$appID]))
{
$newArray[$appID] = $item;
foreach($users as $user)
$newArray[$appID]['users'][] = $user;
}
else
{
$users2 = $newArray[$appID]['users'];
$newArray[$appID] = $item;
foreach($users as $user)
$newArray[$appID]['users'][] = $user;
foreach($users2 as $user)
$newArray[$appID]['users'][] = $user;
}
}
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.
精彩评论