【问题标题】:Extracting json object from array从数组中提取json对象
【发布时间】:2019-03-22 03:30:54
【问题描述】:

我正在使用 php/Laravel,并且我有一个来自 API 的响应,该响应在我的控制器中返回以下格式:

[
  {
  "id": "474",
  "room_id": "14",
  "user_id": "20",
  "name": "121001.webm",
  "fname": "",
  "status": "0",
  "date_recorded": "October 17 2018 07:18:51",
  "size": "396135",
  "is_public": "0",
  "allow_download": "0",
  "privatekey": "",
  "duration": "0",
  "record_path": "https:example/url/test.mp4",
  "record_url": "https:example/url/test.mp4"
  }
]

我相信这是一个数组,里面的数组是我想要数据的 json 对象,所以例如我想要记录 id。 我没有运气使用这些解决方案:

$response->record_url;
$response[0]->record_url;

还尝试编码或解码$response

任何帮助将不胜感激

【问题讨论】:

标签: php json laravel


【解决方案1】:

在 JSON 字符串中,你有一个数组,其中一个元素是一个对象。

现在,根据您的解码方式,您将进入 PHP 和带有 stdClass 对象的数组,或者内部带有关联数组的数组。

//this will return array with stdClass object
$data = json_decode($json);
echo $data[0]->record_url;


//this will return array with associative array
$data = json_decode($json, true);
echo $data[0]['record_url'];

工作代码:https://3v4l.org/TJNQ1

【讨论】:

  • 太棒了!正是我需要的。谢谢
【解决方案2】:

试试这个代码

var_dump(json_decode($response)->record_url);

【讨论】:

    【解决方案3】:

    请参考下面的程序和相应的输出:

    $json = '[
    {
    "id": "474",
    "room_id": "14",
    "user_id": "20",
    "name": "121001.webm",
    "fname": "",
    "status": "0",
    "date_recorded": "October 17 2018 07:18:51",
    "size": "396135",
    "is_public": "0",
    "allow_download": "0",
    "privatekey": "",
    "duration": "0",
    "record_path": "https:example/url/test.mp4",
    "record_url": "https:example/url/test.mp4"
    }
    ]';
    
    $array1 = json_decode($json, false);
    echo $array1[0]->id //This will print the value of id which is 474.
    
    $array2 = json_decode($json, true);
    echo $array2[0]['id'] // This will also print th evalue of id which is 474.
    

    函数json_decode的第二个参数为布尔型,当为TRUE时,返回的对象会被转换成关联数组。

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2015-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多