使用 PHP 从 JSON 提取数据?

Extract data from JSON with PHP?

我想从这个 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 字段和键 php;

很重要

假设上述值存储在名为 data.json 的文件中,我们可以像这样提取值:

$data = file_get_contents('data.json');

//the second parameter turns the objects into an array
$decodedData = json_decode($data, true);

$owner = $decodedData['top_ownerships'][0]['owner'];

$username = $owner['user']['username'];

//echo $username

如果您的 json 文件或数据已正确编码,以上内容将有效。

首先你必须将你的 JSON 存储到一个变量中,我们称之为 $json.

$jsonArray = json_decode($json,true);

并设置您的密钥名称,即您想要的密钥 JSON。

$key = "owner";
$owner= $jsonArray[$key];

你也可以像读物一样阅读:

$owner= $jsonObj->$key;

尝试

$object = json_decode('{"owner": {"user": {"username": "david”},"profile_img_url": "","address": "","config": ""},"quantity": "1"}')

echo $object->owner->user->username

这将使 JSON 成为您可以使用 -> 访问器访问的对象

您的代码是最新的!而且效果很好!

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

你用的是“david”而不是“(双引号)” <----

他们看起来一模一样!

而且您在 JSON 代码的开头和结尾还漏掉了 {}

checkout your json code here it's the best tool for this

<?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;

?>