JSON响应多维数组

时间:2014-08-18 13:49:46

标签: php arrays json multidimensional-array

您好我得到了一个类似下面的JSON响应。我想计算24小时以后的帖子,并检查唯一的用户网址:

{  
   "meta":{  
      "network":"all",
      "query_type":"realtime"
   },
   "posts":[  
      {  
         "network":"facebook",
         "posted":"2014-08-16 08:31:31 +00000",
         "sentiment":"neutral",
         "url":"someURL",
         "user":{  
            "name":"Terance Podolski",
            "url":"someURL",
            "image":"someURL"
         }
      },
      {  
         "network":"facebook",
         "posted":"2014-08-16 08:30:44 +00000",
         "sentiment":"neutral",
         "url":"someURL",
         "user":{  
            "name":"Łukasz Podolski",
            "url":"someURL",
            "image":"someURL"
         }
      },
      {  
         "network":"facebook",
         "posted":"2014-08-16 08:25:39 +00000",
         "sentiment":"neutral",
         "url":"someURL",
         "user":{  
            "name":"Marcin Podolski",
            "url":"someURL",
            "image":"someURL"
         }
      }
]
}

提前致谢。

在@Elias Van Ootegem的帮助下,我解决了问题。代码看起来像这样:

// Json Reponse decodieren
$jsonArray = json_decode($jsonData);



function getMentionsFromLast24H($myArray){
    // set variable exactly one day ago
    $since = new DateTime('-1 day');

    // array where to store timestamps in
    $recent = array();

    foreach ( $myArray -> posts as $post ) {

        try {
            $post -> posted = new DateTime (substr ( $post->posted,0,19 ) );//create DateTime instance
            if ( $post -> posted >= $since )
                $recent[] = $post;//add to array
        } catch ( Exception $e ) {
            echo $e -> getMessage();
            exit(1);
        }

    }

    return $recent;

}

$mentions24h = count(getMentionsFromLast24H($jsonArray));

print_r($mentions24h);

1 个答案:

答案 0 :(得分:3)

非常简单,真的:解码json数据,将posted值与时间进行比较 - 24小时,如果值大于时间24小时,则将其添加到数组中。就是这样,你最终会得到一个包含过去24小时内添加的所有帖子的数组:

$data = json_decode($jsonData);//creates object
$since = new DateTime('yesterday');
$recent = array();//this is the array we'll be constructing
foreach ($data->posts as $post)
{
    $post->posted = new DateTime($post->posted);//create DateTime instance
    if ($post->posted > $since)
        $recent[] = $post;//add to array
}
var_dump($recent);//this is the array you're after

这就是它的全部内容。