使用字段值对数组数据进行分组

时间:2013-07-21 22:19:57

标签: php arrays sorting grouping

我有一个包含当前用户的最后关注者的数组新闻源,如下所示:

$newsFeed=array(
1 => array(
'follower'=>'1',
'following'=>'5',
'datecreation'=>'2013-07-12 15:10:34'
),
2=>array(
'follower'=>'6',
'following'=>'5',
'datecreation'=>'2013-07-12 12:30:56'
),
3=>array(
'follower'=>'7',
'following'=>'5',
'datecreation'=>'2013-05-12 19:08:00'
)
);

我想要做的是缩短新闻Feed,将当天的项目放在一个数组中,上一个表格中的第1项和第2项。如下:

 $newsFeed=array(
    1 => array(
    'follower'=>array('1','6'),
    'following'=>'5',
    'datecreation'=>'2013-07-12'
    ),
    3=>array(
    'follower'=>'7',
    'following'=>'5',
    'datecreation'=>'2013-05-12 19:08:00'
    )
    );

请注意,在结果中,我使用key = 2和key = 1删除了数组,并且将跟随者的id放在一个数组中,我将其放入一个新数组中。

是否有可以提供帮助的PHP功能?

1 个答案:

答案 0 :(得分:0)

最后,我找到了解决方案,这是一个建议的解决方案...将来可能会出现更多关于可能的错误或异常的修改。

这是我建议的解决方案

$creationDate1 = false;
        foreach ($newsFeed as $key => $feed) {

            /*             * **followers** */
            if ($feed['type'] == 'follow') { //test if the current row is a follow type
                $creationDate = DateTime::createFromFormat("Y-m-d H:i:s", $feed['creationdate']);
                $creationDate = $creationDate->format('Y-m-d'); //drop H:i:s from date

                if ($creationDate != $creationDate1) {  
                    $followKey = $key;
                    $followersArray = array();
                }


                $followersArray[] = $feed['follower']; //array for followers ids


                unset($newsFeed[$key]);//remove the current row

                if ($creationDate != $creationDate1) { // if follow has not the same date as the previous one


                    $newsFeed[$followKey] = array(
                        'follower' => $followersArray,
                        'following' => $feed['following'],
                        'creationdate' => $feed['creationdate']
                    );//add row, with the datetime
                } else { //add row, with date, and without time.
                    $newsFeed[$followKey] = array(
                        'follower' => $followersArray,
                        'following' => $feed['following'],
                        'creationdate' => $creationDate
                    );
                }

                $creationDate1 = $creationDate; //$creationDate1=date of the current row.
            }
        } 

任何改进,以及编辑或建议都将受到赞赏