如何从 json url 获取特定数据

How to get particular data from json url

我在 php url 中有以下 Json 数据 文件名:house.php

{
"Error": "",
"ErrorCode": 0,
"Guid": "",
"Id": 0,
"Success": true,
"Value": [
{
"MAIN": 225,
"PHASE": 219418523,
"G": "7TH Division",
"GI": "2031892",
"DOOR": "8907",
"Gate": {
    "RG": 2,
    "BNS": "4 Window",
    "BS": {
    "SB1": 2
    },
    "TQ": [
    {
        "Key": 1,
        "Value": {
        "T1": 2
        }
    },
    {
        "Key": 2,
        "Value": {}
    }
    ],
    "MR": -1,
    "MS": 600
},
"AA": "81",
"AI": "8745524"
},
{
"MAIN": 300,
"PHASE": 219418523,
"G": "8TH Division",
"GI": "4526892",
"DOOR": "8877",
"GATE": {
    "RG": 2,
    "BNS": "5 Window",
    "BS": {
    "SB1": 2
    },
    "TQ": [
    {
        "Key": 1,
        "Value": {
        "T1": 2
        }
    },
    {
        "Key": 2,
        "Value": {}
    }
    ],
    "MR": -1,
    "MS": 600
},
"AA": "91",
"AI": "8758421"
}]}

我需要特定数据 "G"、"G1"、"DOOR"、"AA"、A1" 单独显示在我的新 php 文件中:

completehouse.php in json format 要提供什么代码来获取特定数据。

    <?php
$url="house.php";
$text = file_get_contents($url);
header('Content-Type: application/json');
echo $text;
?>

目前我每次都通过使用转换数据手动使用 https://codebeautify.org/online-json-editor 查询:[*].{G: G, G1: G1, DOOR: DOOR, AA: AA, AI: AI} 并得到输出

{
      "Error": "",
      "ErrorCode": 0,
      "Guid": "",
      "Id": 0,
      "Success": true,
      "Value": [
{
          "G": "7TH DIVISION",
          "G1": "2031892",
          "DOOR": "8907",
          "AA": "81",
          "AI": "8745524"
        },
{
          "G": "8TH DIVISION",
          "G1": "4526892",
          "DOOR": "8877",
          "AA": "85",
          "AI": "8759544"
        }
      ]
    }

请有人帮我解决我的手工工作并节省我的时间。

您可以 decode 您的 json 然后得到您想要的确切值。

$json = '....';
$parsed = json_decode($json,true);
$result = [];
if($parsed['Success']){ // check if your api json response is true. 
    foreach($parsed['Value'] as $val){
        if($val['AI']> = 9000000){
        $result[] = [
            "G"=> $val['G'],
            "GI"=> $val['GI'],
            "DOOR"=> $val['DOOR'],
            "AA"=> $val['AA'],
            "AI"=> $val['AI']
         ];
         }
         // or what you want.
    }
}

echo json_encode($result);

demo

因为您只需要操作值列,所以下面的代码将保持所有值相同,但从值中获取特定列。

$url="house.php";
$text = file_get_contents($url);

$data = json_decode($text, true);

if ($data['Success'] === true) {
    $v = [];
    $columns = ["G", "GI", "DOOR", "AA", "AI"];
    for ($i = 0; $i< count($data['Value']); $i++) {
        foreach ($data['Value'][$i] as $key => $val) {
            if (in_array($key, $columns)) {
                $v[$key] = $val;
            }
        }
        $data['Value'][$i] = $v;
    }
}

$text = json_encode($data);