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

时间:2011-04-28 08:02:04

标签: 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]); 
        }
    }  

3 个答案:

答案 0 :(得分: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提示:)

答案 1 :(得分:0)

如果我没记错的话,json_decode默认情况下不返回数组,而是一个对象。如果要对其进行foreach(),则必须显式请求它返回一个数组。

答案 2 :(得分:0)

是的,json_decode默认情况下不会返回数组,因为该函数的第二个参数允许返回值成为关联数组,默认情况下为false。

$assoc = false

这意味着如果您仅使用以下一个参数调用json_decode函数

json_decode($myjson);

...您将得到一个对象。 但是,定义第二个参数:boolean值,它将决定它是关联数组还是下面的对象:

json_decode($myjson, true);

这将返回一个associative array,其键为对象键,值为对象条目/值。