php如何组合2个json数据并按日期回显结果顺序?

时间:2011-02-27 10:01:52

标签: php json

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

有2个json数据,如何组合它们并回显按日期排序的结果? 我需要一个结果:

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

由于

3 个答案:

答案 0 :(得分:2)

使用 json_decode 将json字符串解码为数组,然后使用任何排序算法对数组进行排序。

答案 1 :(得分:0)

你必须做一些工作来组合它们。要获得类似于您提供的排序结果,您需要将第二个json字符串的“item”数组与第一个json字符串的数组“body”组合在一起。要比较日期,请注意两个json字符串的字段有两个不同的名称:“time”和“date”,这必须在sort函数中处理。

结构更好一点:

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

答案 2 :(得分:0)

这样的东西?

<?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;
    }
}