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

我有一个 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


手掌心
浏览 166回答 3
3回答

慕码人2483693

您的 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;希望这对你有帮助。

潇湘沐

您可以将 JSON 转换为数组并通过键访问元素$jArr = json_decode($string, true);访问元素$jArr['data']['name']

慕侠2389804

您必须从 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: 123Printing the customer id using an array: 123
打开App,查看更多内容
随时随地看视频慕课网APP