php数组按月和年分组

时间:2016-02-10 06:20:41

标签: php arrays json

我正在为网络服务工作,我有按月分组的json编码数组

现有:

{"news":[
{
"July 2015":[
{
"movie_id":"123",
"movie_name":"movie1",
"news_Id":"12",
"news_Heading":"heading3",
"date_time":"2015-07-10 00:00:00"
}, 
{
"movie_id":"123",
"movie_name":"movie1",
"news_Id":"11",
"news_Heading":"heading2",
"date_time":"2015-07-01 00:00:00"
}
],
"June 2015":[
{
"movie_id":"123",
"movie_name":"movie1",
"news_Id":"10",
"news_Heading":"heading1",
"date_time":"2015-06-22 00:00:00"
}]
}]
}

这是我现在得到的输出。那么请你们帮我找出下面的json数组吗? 寻找

{"news":[
    {
    "date":"July 2015",
    "Content":[
    {
    "movie_id":"123",
    "movie_name":"movie1",
    "news_Id":"12",
    "news_Heading":"heading3",
    "date_time":"2015-07-10 00:00:00"
    }, 
    {
    "movie_id":"123",
    "movie_name":"movie1",
    "news_Id":"11",
    "news_Heading":"heading2",
    "date_time":"2015-07-01 00:00:00"
    }
    ],
   "date":"June 2015",
   "Content":[ {
    "movie_id":"123",
    "movie_name":"movie1",
    "news_Id":"10",
    "news_Heading":"heading1",
    "date_time":"2015-06-22 00:00:00"
   }]
}] }

代码

while($star_result=mysql_fetch_array($select_news))
{
$timestamp = strtotime($star_result["date_time"]);
$tmp["movie_id"]=$movie_id;                     
$tmp["movie_name"]=$rtitle[0];                              
$tmp["news_Id"] = $star_result['news_id'];                           
$tmp["news_Heading"] =stripslashes($star_result['news_heading']);
$tmp1["news_datetime1"] = date('F Y', $timestamp);

if(isset($final_array[$tmp1['news_datetime1']])) 
{
 $final_array[$tmp1['news_datetime1']][] = $tmp; // news with same date   
} 
else 
{
 $final_array[$tmp1['news_datetime1']] = array($tmp); // news with new date
}
}
$tmp3['news'] =  array($final_array);
//$tmp3['news'] = array('date' => array($final_array));
$array = json_decode(json_encode($tmp3), true);
header('Content-Type: application/json');
echo json_encode($array);

1 个答案:

答案 0 :(得分:1)

您需要将两个月的元素拆分为两个单个对象,否则您将拥有重复的日期和时间。内容。

以下代码符合您的期望:

// $input contains the input json string
$json = json_decode($input, true);
$outputArray = array('news' => array());

foreach($json['news'] as $news) {
    foreach($news as $month => $entries) {
        $monthNews = array(
            'date' => $month,
            'Content' => array()
        );  

        foreach($entries as $entry) {
            $monthNews['Content'][] = $entry;
        }

        $outputArray['news'][] = $monthNews;
    }
}

echo json_encode($outputArray);