简体   繁体   中英

php array group by month and year

i'm working for the web services, i have the json encoded array with group by month, year

Existing:

{"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"
}]
}]
}

This is the output which i'm getting now. so could you guys please help me to find out the json array like below? Looking for

{"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"
   }]
}] }

Code

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

You need to split the two month elements into two single objects, otherwise you will have duplicate keys date & Content.

The following code does what you expect:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM