【问题标题】:PHP JSON Array: Illegal string offset 'first_name'PHP JSON 数组:非法字符串偏移 'first_name'
【发布时间】:2017-01-24 11:14:21
【问题描述】:

打印出来的 JSON 类似于:

{
    "c_id": {
        "value": 66
    },
    "first_name": {
        "value": "Joe"
    },
    ...

这来自下面的代码

    $profile = json_encode($this->session->getProfile(), true);
    echo $profile;
    echo $profile['first_name']['value'];

但是,我得到了错误:

 Illegal string offset 'first_name'
 Illegal string offset 'value'

有什么想法吗?我看不出我做错了什么。

谢谢

【问题讨论】:

  • $profile 不再是 array 而是 string
  • json_encode 返回一个字符串
  • 如果这个$this->session->getProfile()应该返回一个JSON字符串,使用json_decode($this->session->getProfile())

标签: php json


【解决方案1】:

如果你想访问数组,你必须解码你的 JSON 数据:

$profile = json_decode($this->session->getProfile(), true);

【讨论】:

  • 如果 $this->session->getProfile() 包含一个 json 字符串,那可能是真的。但显然不是。
  • 抱歉,我不明白您在 json_encode 中的第二个参数“true”应该做什么?
【解决方案2】:

我不确定你想做什么,但一旦你有了

$profile = json_decode($this->session->getProfile(), true);

那么你得到的响应可能是一个字符串,你需要一个对象,反之亦然

【讨论】:

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