Grouping PHP Array on 2 or more different values
I'm creating a recent activity section and I am trying to group similar items. I want to be able to group activities based on type of activity and who did the activity. For instance:
Array
(
[0] => Array
(
[user] => Bill
[type] => photo
[id] => 1
[timestamp] => 12345678
)
[1] => Array
(
[user] => Joe
[type] => photo
[id] => 2
[timestamp] => 12345678
)
[2] => Array
(
[user] => Bill
[type] => comment
[id] => 1
[timestamp] => 12345678
)
[3] => Array
(
[user] => Bill
[type] => photo
[id] => 3
[timestamp] => 12345678
)
)
could turn into this:
Array
(
[0] => Array
(
[user] => Bill
[type] => photo
[items] => Array
(
[0] => Array
(
[id] => 1
[timestamp] => 12345678
)
[1] => Array
(
[id] => 3
[timestamp] => 12345678
)
)
)
[1] => Array
(
[user] => Joe
[type] => photo
[items] => Array
(
[0] => Array
(
[id] => 2
[timestamp] => 12345678
)
)
)
[2] => Array
(
[user] => Bill
[type] => comment
[items] => Array
(
[0] => Array
(
[id] => 1
开发者_StackOverflow社区 [timestamp] => 12345678
)
)
)
)
This is almost what I am trying to do but not quite there: Grouping arrays in PHP
Anyone have an idea?
Your grouping doesn't exactly make sense (it makes a little more sense after your edit), try this:
foreach ($activity as $data) {
$newdata[$data['user']][$data['type']]['id'][]=$data['id'];
$newdata[$data['user']][$data['type']]['timestamp'][]=$data['timestamp'];
}
Edit to reflect your changes in desired output: (and a structure that is a bit more useful)
foreach ($activity as $data) {
$newdata[$data['user']][$data['type']]['items'][]=array('id'=>$data['id'],'timestamp'=>$data['timestamp']);
}
Edit 2:
You have to have some sort of key, in this case its a combo of the username and the type. Then you have to re-index it so its numeric if that actually matters. That should be quite close to exactly what you want:
foreach ($activity as $data) {
$key=$data['user'].'-'.$data['type'];
$newdata[$key]['items'][]=array('id'=>$data['id'],'timestamp'=>$data['timestamp']);
$newdata[$key]['user']=$data['user'];
$newdata[$key]['type']=$data['type'];
}
$newdata=array_values($newdata);
tested:
http://www.ideone.com/3uZdd
Edit 3:
separate dates... this is the idea to get you started, you'll need to do a little more to the original array for this.
foreach ($activity as $data) {
$key=$data['user'].'-'.$data['type'];
$newdata[$key]['items'][$data['day']][]=array('id'=>$data['id'],'timestamp'=>$data['timestamp']);
$newdata[$key]['user']=$data['user'];
$newdata[$key]['type']=$data['type'];
}
$newdata=array_values($newdata);
Try using uasort with a custom function that sorts on the values of user
and type
.
精彩评论