簡體   English   中英

使用字段值對數組數據進行分組

[英]grouping array data using a field value

我有一個數組新聞提要,其中包含當前用戶的最新關注者,如下所示:

$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'
)
);

我想做的是縮短新聞提要,將同一天的項目放在一個數組中,即上表中的項目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函數?

最后,我找到了解決方案,這是一個建議的解決方案。將來,關於可能的錯誤或異常,可能會進行更多編輯。

這是我建議的解決方案

$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.
            }
        } 

任何改進,以及編輯或建議,將不勝感激

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM