get返回的json字符串,我通过php json_encode后,如何取值?

json字符串如下:

{
    "headers": {
        "Content-Type": ["application\/json;charset=utf-8"],
        "Content-Length": ["110"],
    },
    "statusCode": 200
}

我通过 $json=json_encode(上面的返回字符串);
我如何取statusCode的值?
我用$json['statusCode']返回500错误: "message": "Cannot access offset of type string on string"

阅读 981
avatarAI BotBETA

要从 JSON 字符串中获取 statusCode 的值,你需要首先确保你的 JSON 字符串已经被解码为 PHP 对象或数组。json_encode() 函数用于将 PHP 对象或数组转换为 JSON 字符串,而 json_decode() 函数用于将 JSON 字符串解码为 PHP 对象或数组。

在你的例子中,$json 是一个字符串,所以当你尝试用 $json['statusCode'] 去获取值时,PHP 解释器会抛出错误,因为你不能在字符串上使用数组索引。

你需要用 json_decode() 函数将 $json 字符串解码为 PHP 对象或数组,然后才能获取 statusCode 的值。以下是一个例子:

$json = '{"headers": {"Content-Type": ["application\/json;charset=utf-8"],"Content-Length": ["110"]},"statusCode": 200}';
$data = json_decode($json);
echo $data->statusCode;  // 输出:200

在这个例子中,json_decode() 函数将 $json 字符串解码为一个 PHP 对象,然后我们可以通过 $data->statusCode 来获取 statusCode 的值。如果你的 JSON 包含嵌套的数组或对象,你可以通过这种方式来访问它们的值。

2 个回答

encode 是把对象编码为字符串,对字符串编码那不还是字符串嘛。
你应该使用 json_decode

➜ ~ cat test/a.php

<?php
$json = json_decode('{
    "headers": {
        "Content-Type": ["application\/json;charset=utf-8"],
        "Content-Length": ["110"]
    },
    "statusCode": 200
}', true);

print_r($json['statusCode']);

➜ ~ php test/a.php
200%

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题