Grouping PHP Array on 2 or more different values -
i'm creating recent activity section , trying group similar items. want able group activities based on type of activity , did activity. 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 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 [timestamp] => 12345678 ) ) ) )
this trying not quite there: grouping arrays in php
anyone have idea?
your grouping doesn't make sense (it makes little more sense after edit), try this:
foreach ($activity $data) { $newdata[$data['user']][$data['type']]['id'][]=$data['id']; $newdata[$data['user']][$data['type']]['timestamp'][]=$data['timestamp']; }
edit reflect changes in desired output: (and structure bit more useful)
foreach ($activity $data) { $newdata[$data['user']][$data['type']]['items'][]=array('id'=>$data['id'],'timestamp'=>$data['timestamp']); }
edit 2:
you have have sort of key, in case combo of username , type. have re-index numeric if matters. should quite close want:
foreach ($activity $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... idea started, you'll need little more original array this.
foreach ($activity $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);
Comments
Post a Comment