2011-02-27 55 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; 
    } 
} 
相關問題