开发者

php How to combine 2 json data and echo a result order by date?

开发者 https://www.devze.com 2023-02-13 22:13 出处:网络
{\"query\": {\"data\":{ \"item\":[{\"title\":\"some word1\", \"date\":\"Sat, 26 Feb 2011 21:02:01\"}, {\"title\":\"some word2\",
{"query":
{"data":{
"item":[{"title":"some word1",
"date":"Sat, 26 Feb 2011 21:02:01"},
{"title":"some word2",
"date":"Sat, 26 Feb 2011 17:02:01"}]
}}}


{"开发者_如何学运维query":
{"text":{
"body":[{"title":"some word3",
"time":"Sat, 26 Feb 2011 20:22:21"},
{"title":"some word4",
"time":"Sat, 26 Feb 2011 19:11:59"}]
}}}

There have 2 json data, how to combine them and echo a result which is order by date? I need a result like:

some word1 Sat, 26 Feb 2011 21:02:01
some word3 Sat, 26 Feb 2011 20:22:21
some word4 Sat, 26 Feb 2011 19:11:59
some word2 Sat, 26 Feb 2011 17:02:01

Thanks


Use json_decode to decode the json string into an array and then sort the array using any sorting algorithm.


You will have to do some work to combine them. To get a sort result like you provided you need to combine the "item" array of the second json string with the array "body" of the first one. To compare the dates be aware that the fields of the two json string have two different name: "time" and "date", this has to be taken care of in your sort function.

The structures a bit better reabable:

{
   "query":{
      "data":{
         "item":[
            {
               "title":"some word1",
               "date":"Sat, 26 Feb 2011 21:02:01"
            },
            {
               "title":"some word2",
               "date":"Sat, 26 Feb 2011 17:02:01"
            }
         ]
      }
   }
}


{
   "query":{
      "text":{
         "body":[
            {
               "title":"some word3",
               "time":"Sat, 26 Feb 2011 20:22:21"
            },
            {
               "title":"some word4",
               "time":"Sat, 26 Feb 2011 19:11:59"
            }
         ]
      }
   }
}


Something like this?

<?php
$data = array();

// Parse the json into a clean array
$json = json_decode('{"query": 
    {"data":
    { "item":[{"title":"some word1", "date":"Sat, 26 Feb 2011 21:02:01"},
    {"title":"some word2", "date":"Sat, 26 Feb 2011 17:02:01"}] }}} ');

foreach($json->query->data->item as $body){
    $data[strtotime($body->date)][] = $body->title;
}

$json = json_decode(' {"query": 
{"text":
{ "body":[
{"title":"some word3", "time":"Sat, 26 Feb 2011 20:22:21"}, 
{"title":"some word4", "time":"Sat, 26 Feb 2011 19:11:59"}] }}}');

foreach($json->query->text->body as $body){
    $data[strtotime($body->time)][] = $body->title;
}

// Sort the timestamps
ksort($data,SORT_NUMERIC);

// Display the data any way you want
foreach($data as $timestamp => $titles){
    foreach($titles as $title){
        echo $title, ' ', date('r',$timestamp), PHP_EOL;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消