开发者

Can't access array entries using its index/key in PHP

I have done it a thousand times before but for some reason I cant access array entries using their index/key. The only thing I am doing different is reading the json from a file and then using json_decode to populate this particular array of objects. When I use a foreach loop, I get the $post and the $key, but when I use the key to access the same value in the original array using $posts[$key], it returns nothing. I need to unset some specific entries and passing via reference hasnt helped either. Below is the code:

    $contents = fread($fh, filesize($filepath));
    fclose( $fh );
    $posts开发者_高级运维 = (array)json_decode($contents);

    foreach( $posts as $key => &$post ){
        $post_time = strtotime($post->post_date);
        $now = strtotime('now');
        if( ($now - $post_time) > 86400 ){
            unset($posts[$key]); 
        }
    }  


change

$posts = (array)json_decode($contents);

to

$posts = json_decode($contents, true); - it will return array you need.

http://ru2.php.net/manual/en/function.json-decode.php

also you can change $now = strtotime('now'); to $now = time(); and move it out of cycle - it's much faster :)

Tnx @binaryLV for hints :)


If I remember right, json_decode doesn't return an array by default, but an object. You have to explicitly request that it returns an array instead if you want to foreach() over it.


Yeah, json_decode doesn't return an array by default because the second parameter to the function that allows the return value to be an associative array is false by default.

$assoc = false

This means if you call the json_decode function with only one argument as below

json_decode($myjson);

...you will get an object. But defining a second argument: a boolean value, it will decide whether it will be an associate array or just an object as below:

json_decode($myjson, true);

This will return an associative array with the keys as the object keys and the values as the object entries/values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜