2011-02-27 51 views
0
{"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数据,如何将它们结合起来并回显一个按日期排序的结果? 我需要一个像结果:php如何结合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 

感谢

回答

2

使用json_decode将JSON字符串解码成一个数组,然后使用任何排序算法排序数组。

+0

不要忘记你应该使用'array_merge'来合并2个数组! – nico

+0

你有这样的演示或教程吗?谢谢。 – cj333

0

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

结构好一点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" 
      } 
     ] 
     } 
    } 
} 
+0

PHP有一个'json_decode'函数,可以为你做所有的工作。 – nico

+0

当然,但它不会神奇地完成OP所要求的排序。 –

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; 
    } 
} 
相关问题