【问题标题】:Can't retrieve value of JSON Object attr after json_encode in PHP在 PHP 中的 json_encode 之后无法检索 JSON 对象属性的值
【发布时间】:2015-11-11 18:02:55
【问题描述】:

我无法在这个(显然是有效的)JSON 对象中获取 image 属性的值:

echo var_dump($result);

array(1) {
  ["images"]=>
  array(1) {
    [0]=>
    array(1) {
      ["src"]=>
      string(112) "http://staticf5a.diaadia.info/sites/default/files/styles/landscape_310_155/public/nota_periodistica/taxis_13.jpg"
    }
  }
}

$jsonResult = json_encode($result); //result is an array of arrays
echo $jsonResult;

{"images":[{"src":"http:\/\/staticf5a.diaadia.info\/sites\/default\/files\/styles\/landscape_310_155\/public\/nota_periodistica\/taxis_13.jpg"}]}

echo $jsonResult->images; //show nothing

这个 sn-p 几天前还在工作,日志 (ini_set('display_errors', '0');) 没有显示任何相关内容。

【问题讨论】:

  • 现在发生了什么?
  • 所以,你对其进行编码,并尝试从字符串中获取属性,还是我理解错误?
  • 我有一个基于 $jsonResult $jsonResult->images != null 的条件在这种情况下应该为真,但变为假。
  • 对于 JSON 对象,请尝试 ->{'images'}
  • json_encode 返回一个字符串,然后您可以对其进行 json_decode,以获取一个具有图像元素的对象

标签: php json object encode


【解决方案1】:

编码后,$jsonResult 只是一个字符串,如果不先解码,您将无法访问已编码 JSON 的任何元素。

看看 PHP 的 ``json_decode'' 函数:http://php.net/manual/pl/function.json-decode.php

它将 JSON 转换回关联数组或对象。

无论如何,我不知道您为什么将关联数组编码为 JSON 并尝试在那里访问 images 而不是从数组本身中获取它。

【讨论】:

    【解决方案2】:

    您正在尝试从此处的字符串中获取属性。 json_encode() 将对象的 json 表示形式返回为字符串。那个字符串你可以用json_decode()变成一个实际的对象

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多