【问题标题】:Can't access array entries using its index/key in PHP无法使用 PHP 中的索引/键访问数组条目
【发布时间】:2011-08-14 12:04:43
【问题描述】:

我之前已经做过一千次了,但由于某种原因,我无法使用它们的索引/键访问数组条目。我唯一不同的是从文件中读取 json,然后使用 json_decode 填充这个特定的对象数组。当我使用 foreach 循环时,我得到了 $post 和 $key,但是当我使用 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]); 
        }
    }  

【问题讨论】:

  • print_r($posts) 返回什么?
  • print_r($posts)检查结构并尝试json_decode($contents, true)
  • `                                          ₄         ₄    ₄    ₄
  • 我在把代码放在这里之前删除了几个 print_r($posts)...一切都很好...就像我提到的,在 foreach 中,我得到 $key 和 $post,只有当我尝试将 $key 与 $posts 一起使用,在这种情况下取​​消设置,我什么也得不到。
  • json_decode($contents, true) 成功了...我应该检查手册...将其类型转换为数组似乎对我有用,但显然它有问题。非常感谢队友:)

标签: php arrays indexing key


【解决方案1】:

改变

$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 提示 :)

【讨论】:

  • 也许试着解释一下为什么他需要这样改变
  • 我建议使用time() 而不是date()... 甚至更好 - $_SERVER['REQUEST_TIME']
  • $posts = json_decode($contents, true);工作。感谢您的及时回复和建议:)
【解决方案2】:

如果我没记错的话,json_decode 默认不返回数组,而是返回一个对象。如果你想对它进行 foreach() ,你必须明确要求它返回一个数组。

【讨论】:

    【解决方案3】:

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

    $assoc = false
    

    这意味着如果您调用 json_decode 函数时只有一个参数,如下所示

    json_decode($myjson);
    

    ...你会得到一个对象。 但是定义第二个参数:boolean 值,它将决定它是关联数组还是只是一个对象,如下所示:

    json_decode($myjson, true);
    

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

    【讨论】:

      猜你喜欢
      • 2014-03-08
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      相关资源
      最近更新 更多