簡體   English   中英

php如何組合2個json數據並按日期回顯結果順序?

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

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

謝謝

使用json_decode將json字符串解碼為數組,然后使用任何排序算法對數組進行排序。

你將不得不做一些工作來組合它們。 要獲得類似於您提供的排序結果,您需要將第二個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"
            }
         ]
      }
   }
}

像這樣的東西?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM