PHP-检索JSON数据和值

时间:2018-10-01 23:05:58

标签: php json

我是PHP和JSON的新手,但遇到问题,我想从JSON检索项目和值:

{
  "status": true,
  "webhook_type": 100,
  "data": {
    "product": {
      "id": "lSEADIQ",
      "attachment_id": null,
      "title": "Registration",
      "description": null,
      "image": null,
      "unlisted": false,
      "type": "service",
      "price": 1,
      "currency": "EUR",
      "email": {
        "enabled": false
      },
      "stock_warning": 0,
      "quantity": {
        "min": 1,
        "max": 1
      },
      "confirmations": 1,
      "custom_fields": [
        {
          "name": "Forum username",
          "type": "text",
          "required": true
        }
      ],
      "gateways": [
        "Bitcoin"
      ],
      "webhook_urls": [],
      "dynamic_url": "",
      "position": null,
      "created_at": "2018-10-01 12:51:12",
      "updated_at": "2018-10-01 12:55:46",
      "stock": 9223372036854776000,
      "accounts": []
    },
    "order": {
      "id": "8e23b496-121a-4dc6-8ec4-c45835680db2",
      "created_at": "Tue, 02 Oct 2018 00:54:56 +0200",
      "paid_at": null,
      "transaction_id": null,
      "confirmations": 1,
      "required_confirmations": 3,
      "received_amount": 0,
      "crypto_address": "1NeNQws7JLbTr6bjekfeaXSV7XiyRsv7V8",
      "crypto_amount": "0.4815",
      "quantity": 1,
      "price": 19.99,
      "currency": "EUR",
      "exchange_rate": "1.21",
      "gateway": "BTC",
      "email": "webhook@site.gg",
      "ip_address": "123.456.789.111",
      "agent": {
        "geo": {
          "ip": "214.44.18.6",
          "iso_code": "US",
          "country": "United States"
        },
        "data": {
          "is_mobile": false,
          "is_table": false,
          "is_desktop": true,
          "browser": {
            "name": "Chrome",
            "version": "63.0.3239.132"
          }
        }
      },
      "custom_fields": [
        {
          "name": "user_id",
          "value": 184191
        }
      ],
      "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3)"
    }
  }
}

我想从数据->订单中检索项目,例如“ id”或“ ip_address”。 谢谢您的阅读,我希望有人能对此有所帮助,因为我迷路了,我最近才开始编写代码,我正努力学习很多东西。

致谢!

2 个答案:

答案 0 :(得分:0)

您可以从JSON数据中提取需要的数组。您也可以使用循环来读取订单数组中的所有数据。

$array = json_decode($json, true);

$verbose = $array['data'];
$orderArray = $verbose['order'];

print_r($orderArray);

echo $orderArray['id'];
echo $orderArray['ip_address'];

答案 1 :(得分:0)

test.json是您上载的json,将其放置在名为test.json的文件中,并确保将其放置在同一目录中。

<?php

$load = file_get_contents("test.json") or die("JSON load failed");    
$json_a = json_decode($load, true);
print $json_a['data']['order']['ip_address'] . "\n"; 

?>

礼物:

123.456.789.111

我的回答是从文件中读取JSON,就像直接将其转储到您的代码中一样(确实如此),这会使代码的可读性降低,文件也变得更加混乱。

如果您不想将文件放在同一目录中,只需指定完整的文件路径。例如。 file_get_contents("this/dir/here/test.json");

您可以了解here的工作原理,json_decode的工作原理非常重要,我们需要向其传递true参数以构成arrays associative