{"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 ($query->data->item as $result) {
echo $result->title;
echo strtotime($result->date);
}{"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 ($query->text->body as $result1) {
echo $result1->title;
echo strtotime($result1->time);
}有2个JSON表列,通过json_decode及foreach可以分别获取各自的资料。
如何将2个foreach的结果合并,并按时间降序排列?谢谢。
我需要的输出结果为:
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

解决方案 »

  1.   


    //大体思路如下
    $temp = array('key'=>array());//读入第一个JSON入数组
    foreach ($query->data->item as $result) {
        $tmp = strtotime($result->date);
        $temp['key'][] = $tmp;
        $temp[$tmp] = array($result->title, $result->date);//这里可组合成你要的格式
    }
    //读入第二个JSON入数组
    foreach ($query->text->body as $result1) {
        $tmp = strtotime($result->time);
        $temp['key'][] = $tmp;
        $temp[$tmp] = array($result->title, $result->time);
    }
    //排序,然后按照顺序输出
    natsort($temp['key']);
    foreach( $temp['key'] as $k => $v ){
        echo implode(' ', $v).'<br/>';
    }
    unset($tmp,$temp,$result,$k,$v);
      

  2.   

    楼主你说的是json_encode才对,decode是解开了!
      

  3.   

    gzty, 你好。
    print_r($temp[$tmp]);只能输出循环里的一个数值啊。
      

  4.   

    $json1 = <<<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"}]
    }}}
    JSON;$json2 = <<<JSON
    {"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"}]
    }}}
    JSON;$arr = array();$obj1 = json_decode($json1);
    foreach ($obj1->query->data->item as $item)
    $arr[] = array('title' => $item->title, 'time' => $item->date);$obj2 = json_decode($json2);
    foreach ($obj2->query->text->body as $item)
    $arr[] = array('title' => $item->title, 'time' => $item->time);function cmp($a, $b)
    {
    $t1 = strtotime($a['time']);
    $t2 = strtotime($b['time']);
    if ($t1 == $t2) return 0;
    return $t1 > $t2 ? -1 : 1;
    }usort($arr, 'cmp');foreach ($arr as $item)
    echo $item['title'], ' ', $item['time'], '<br/>';