为了账号安全,请及时绑定邮箱和手机立即绑定

如何打印解析为 php 对象的 json 字符串

如何打印解析为 php 对象的 json 字符串

PHP
手掌心 2022-01-02 17:20:31
我有一个 JSON 字符串,我将其解析为 PHP 对象,我想从字符串中打印某些值,如何打印我需要的确切值。我提供了下面的代码{  "data":    {      "id":123,       "name": "abc",       "gsm":"1133",       "metadata":       {        "cart_id":13243      },       "customer":       {        "id":123,        "email": "a@ma.co"      }    }}json_decode($string);例如“名称”:abc,我只想打印 abc
查看完整描述

3 回答

?
慕码人2483693

TA贡献1860条经验 获得超9个赞

您的 JSON 字符串无效,您在其中缺少括号。此外,字符串值必须在 json 中包含引号。你的字符串应该像


$string= '{

  "data": {

    "id": 123,

    "name": "abc",

    "gsm": 1133,

    "metadata": {

      "cart_id": 13243

    },

    "customer": {

      "id": 123,

      "email": "a@ma.co"

    }

  }

}';


$response = json_decode($string);

print_r($response->data->name);

die;

希望这对你有帮助。


查看完整回答
反对 回复 2022-01-02
?
潇湘沐

TA贡献1816条经验 获得超6个赞

您可以将 JSON 转换为数组并通过键访问元素

$jArr = json_decode($string, true);

访问元素

$jArr['data']['name']


查看完整回答
反对 回复 2022-01-02
?
慕侠2389804

TA贡献1719条经验 获得超6个赞

您必须从 json 解码访问元素,如下所示:


$JSON = '{

    "data":{

        "id":123,

        "name": abc,

        "gsm":1133,

        "metadata":{

            "cart_id":13243

        },

        "customer":{

            "id":123,

            "email": "a@ma.co"

        }

    }

}'; //There were three errors, you have to to use ' insted of " for including the JSON string, you missed one '}' and you forgot the "" in the 'email' value under 'customer' section


$object = json_decode($JSON);

echo 'Printing the customer id using an object: '.$object->data->customer->id.PHP_EOL.PHP_EOL;


$array = json_decode($JSON, true);

echo 'Printing the customer id using an array: '.$array['data']['customer']['id'];

此代码打印:


Printing the customer id using an object: 123


Printing the customer id using an array: 123


查看完整回答
反对 回复 2022-01-02
  • 3 回答
  • 0 关注
  • 165 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信