无法使用PHP中的索引/键访问数组条目

Uza*_*han 1 php arrays indexing key

我以前做了一千次但由于某种原因我无法使用他们的索引/键访问数组条目.我唯一不同的是从文件中读取json,然后使用json_decode填充此特定的对象数组.当我使用foreach循环时,我得到$ post和$ key,但是当我使用密钥使用$ posts [$ key]访问原始数组中的相同值时,它什么都不返回.我需要取消设置一些特定的条目,并通过引用传递也没有帮助.以下是代码:

    $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]); 
        }
    }  
Run Code Online (Sandbox Code Playgroud)

Emm*_*man 7

更改

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

$posts = json_decode($contents, true); - 它将返回您需要的数组.

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

你也可以改变$now = strtotime('now');$now = time();并将其移出循环-它的速度更快:)

Tnx @binaryLV提示:)