使用 PHP 从 JSON 中提取数据?

迈赫迪

我想从这个 Json 中获取用户名(david)的数据,我看到了类似的问题,我尝试了 100 多次,但我不能,如果可能的话,我需要确切的答案。提前致谢

{
    "related_assets": [],
  "orders": [],
  "auctions": [],
  "supports_wyvern": true,
  "top_ownerships": [
    {
      "owner": {
        "user": {
          "username": "david"
        },
        "",
        "address": "",
        "config": ""
      },
      "quantity": "1"
    }
  ],
  "ownership": null,
  "highest_buyer_commitment": null
}

我编码如下:

<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
    //the second parameter turns the objects into an array
    $decodedData = json_encode($response, true);
    $owner = $decodedData['top_ownerships'][0]['owner'];
    $username = $owner['user']['username'];
    echo $username;


}

输出是“请帮忙谢谢

编码器

您的代码是完全最新的!它就像魅力一样!

但是您在 JSON 代码中犯了一个非常模棱两可的错误

你正在使用这个“而不是”(双引号)那里“大卫”<----

它们看起来完全一样!

并且您在 JSON 代码的开头和结尾错过了 {}

在这里检查您的 json 代码,这是最好的工具

<?php

$code = '{
    "top_ownerships": [{
        "owner": {
            "user": {
                "username": "david"
            },
            "profile_img_url": "",
            "address": "",
            "config": ""
        },
        "quantity": "1"
    }]
}';

  $decodedData = json_decode($code, true);

  $owner = $decodedData['top_ownerships'][0]['owner'];
  $username = $owner['user']['username'];
  echo $username;

?>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章