как получить доступ к элементу адреса из нижнего вложенного объекта json В PHP

#php #json

#php #json

Вопрос:

Я хочу получить доступ к addressLine , adminDistrict из элемента адреса, который хранится в формате json В PHP

 {
  "authenticationResultCode": "ValidCredentials",
  "brandLogoUri": "http://dev.virtualearth.net/Branding/logo_powered_by.png",
  "copyright": "Copyright © 2019 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
  "resourceSets": [
    {
      "estimatedTotal": 1,
      "resources": [
        {
          "__type": "Location:http://schemas.microsoft.com/search/local/ws/rest/v1",
          "bbox": [
            40.75594078242932,
            -74.0022632570927,
            40.76366621757067,
            -73.98866508290732
          ],
          "name": "471 W 42nd St, New York, NY 10036",
          "point": {
            "type": "Point",
            "coordinates": [
              40.7598035,
              -73.99546417
            ]
          },
          "address": {
            "addressLine": "471 W 42nd St",
            "adminDistrict": "NY",
            "adminDistrict2": "New York Co.",
            "countryRegion": "United States",
            "formattedAddress": "471 W 42nd St, New York, NY 10036",
            "intersection": {
              "baseStreet": "W 42nd St",
              "secondaryStreet1": "10th Ave",
              "intersectionType": "Near",
              "displayName": "W 42nd St and 10th Ave"
            },
            "locality": "New York",
            "postalCode": "10036"
          },
          "confidence": "High",
          "entityType": "Address",
          "geocodePoints": [
            {
              "type": "Point",
              "coordinates": [
                40.7598035,
                -73.99546417
              ],
              "calculationMethod": "Rooftop",
              "usageTypes": [
                "Display"
              ]
            }
          ],
          "matchCodes": [
            "Good"
          ]
        }
      ]
    }
  ],
  "statusCode": 200,
  "statusDescription": "OK",
  "traceId": "d551494203554f058cd3e2e72582f7b1|HK20271557|7.7.0.0|HK01EAP000001D0"
}

{
  "authenticationResultCode": "ValidCredentials",
  "brandLogoUri": "http://dev.virtualearth.net/Branding/logo_powered_by.png",
  "copyright": "Copyright © 2019 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
  "resourceSets": [
    {
      "estimatedTotal": 1,
      "resources": [
        {
          "__type": "Location:http://schemas.microsoft.com/search/local/ws/rest/v1",
          "bbox": [
            40.75594078242932,
            -74.0022632570927,
            40.76366621757067,
            -73.98866508290732
          ],
          "name": "471 W 42nd St, New York, NY 10036",
          "point": {
            "type": "Point",
            "coordinates": [
              40.7598035,
              -73.99546417
            ]
          },
          "address": {
            "addressLine": "471 W 42nd St",
            "adminDistrict": "NY",
            "adminDistrict2": "New York Co.",
            "countryRegion": "United States",
            "formattedAddress": "471 W 42nd St, New York, NY 10036",
            "intersection": {
              "baseStreet": "W 42nd St",
              "secondaryStreet1": "10th Ave",
              "intersectionType": "Near",
              "displayName": "W 42nd St and 10th Ave"
            },
            "locality": "New York",
            "postalCode": "10036"
          },
          "confidence": "High",
          "entityType": "Address",
          "geocodePoints": [
            {
              "type": "Point",
              "coordinates": [
                40.7598035,
                -73.99546417
              ],
              "calculationMethod": "Rooftop",
              "usageTypes": [
                "Display"
              ]
            }
          ],
          "matchCodes": [
            "Good"
          ]
        }
      ]
    }
  ],
  "statusCode": 200,
  "statusDescription": "OK",
  "traceId": "d551494203554f058cd3e2e72582f7b1|HK20271557|7.7.0.0|HK01EAP000001D0"
}
  

Комментарии:

1. присвойте этот JSON переменной в PHP. И использовать json_decode() для этой переменной

2. зачем использовать json_decode(), когда он уже поставляется в формате json

3. преобразовать его в массив

4. $jsonData = json_decode($result, true), и как получить доступ к адресной строке из массива

5. проверьте ответ…

Ответ №1:

вам нужно получить к нему доступ, присвоив его переменной, например, скажем

 let a = { "authenticationResultCode": "ValidCredentials", "brandLogoUri": "http://dev.virtualearth.net/Branding/logo_powered_by.png", "copyright": "Copyright © 2019 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.", "resourceSets": [ { "estimatedTotal": 1, "resources": [ { "__type": "Location:http://schemas.microsoft.com/search/local/ws/rest/v1", "bbox": [ 40.75594078242932, -74.0022632570927, 40.76366621757067, -73.98866508290732 ], "name": "471 W 42nd St, New York, NY 10036", "point": { "type": "Point", "coordinates": [ 40.7598035, -73.99546417 ] }, "address": { "addressLine": "471 W 42nd St", "adminDistrict": "NY", "adminDistrict2": "New York Co.", "countryRegion": "United States", "formattedAddress": "471 W 42nd St, New York, NY 10036", "intersection": { "baseStreet": "W 42nd St", "secondaryStreet1": "10th Ave", "intersectionType": "Near", "displayName": "W 42nd St and 10th Ave" }, "locality": "New York", "postalCode": "10036" }, "confidence": "High", "entityType": "Address", "geocodePoints": [ { "type": "Point", "coordinates": [ 40.7598035, -73.99546417 ], "calculationMethod": "Rooftop", "usageTypes": [ "Display" ] } ], "matchCodes": [ "Good" ] } ] } ], "statusCode": 200, "statusDescription": "OK", "traceId": "d551494203554f058cd3e2e72582f7b1|HK20271557|7.7.0.0|HK01EAP000001D0" }
  

затем получите к нему доступ следующим образом

 console.log(a.resourceSets[0].resources[0].address)
  

Комментарии:

1. Они запросили это На PHP

Ответ №2:

 <?php
/*
if Array of JSON Object is returned then
Use following
*/
$json = '[{
  "authenticationResultCode": "ValidCredentials",
  "brandLogoUri": "http://dev.virtualearth.net/Branding/logo_powered_by.png",
  "copyright": "Copyright © 2019 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
  "resourceSets": [
    {
      "estimatedTotal": 1,
      "resources": [
        {
          "__type": "Location:http://schemas.microsoft.com/search/local/ws/rest/v1",
          "bbox": [
            40.75594078242932,
            -74.0022632570927,
            40.76366621757067,
            -73.98866508290732
          ],
          "name": "471 W 42nd St, New York, NY 10036",
          "point": {
            "type": "Point",
            "coordinates": [
              40.7598035,
              -73.99546417
            ]
          },
          "address": {
            "addressLine": "471 W 42nd St",
            "adminDistrict": "NY",
            "adminDistrict2": "New York Co.",
            "countryRegion": "United States",
            "formattedAddress": "471 W 42nd St, New York, NY 10036",
            "intersection": {
              "baseStreet": "W 42nd St",
              "secondaryStreet1": "10th Ave",
              "intersectionType": "Near",
              "displayName": "W 42nd St and 10th Ave"
            },
            "locality": "New York",
            "postalCode": "10036"
          },
          "confidence": "High",
          "entityType": "Address",
          "geocodePoints": [
            {
              "type": "Point",
              "coordinates": [
                40.7598035,
                -73.99546417
              ],
              "calculationMethod": "Rooftop",
              "usageTypes": [
                "Display"
              ]
            }
          ],
          "matchCodes": [
            "Good"
          ]
        }
      ]
    }
  ],
  "statusCode": 200,
  "statusDescription": "OK",
  "traceId": "d551494203554f058cd3e2e72582f7b1|HK20271557|7.7.0.0|HK01EAP000001D0"
},
{
  "authenticationResultCode": "ValidCredentials",
  "brandLogoUri": "http://dev.virtualearth.net/Branding/logo_powered_by.png",
  "copyright": "Copyright © 2019 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
  "resourceSets": [
    {
      "estimatedTotal": 1,
      "resources": [
        {
          "__type": "Location:http://schemas.microsoft.com/search/local/ws/rest/v1",
          "bbox": [
            40.75594078242932,
            -74.0022632570927,
            40.76366621757067,
            -73.98866508290732
          ],
          "name": "471 W 42nd St, New York, NY 10036",
          "point": {
            "type": "Point",
            "coordinates": [
              40.7598035,
              -73.99546417
            ]
          },
          "address": {
            "addressLine": "471 W 42nd St",
            "adminDistrict": "NY",
            "adminDistrict2": "New York Co.",
            "countryRegion": "United States",
            "formattedAddress": "471 W 42nd St, New York, NY 10036",
            "intersection": {
              "baseStreet": "W 42nd St",
              "secondaryStreet1": "10th Ave",
              "intersectionType": "Near",
              "displayName": "W 42nd St and 10th Ave"
            },
            "locality": "New York",
            "postalCode": "10036"
          },
          "confidence": "High",
          "entityType": "Address",
          "geocodePoints": [
            {
              "type": "Point",
              "coordinates": [
                40.7598035,
                -73.99546417
              ],
              "calculationMethod": "Rooftop",
              "usageTypes": [
                "Display"
              ]
            }
          ],
          "matchCodes": [
            "Good"
          ]
        }
      ]
    }
  ],
  "statusCode": 200,
  "statusDescription": "OK",
  "traceId": "d551494203554f058cd3e2e72582f7b1|HK20271557|7.7.0.0|HK01EAP000001D0"
}]';

$array = json_decode($json);
foreach($array as $sub_array) {
    echo $sub_array->resourceSets[0]->resources[0]->address->addressLine . "<br/>";
    echo $sub_array->resourceSets[0]->resources[0]->address->adminDistrict . "<br/>";
}

/*
And if single JSON Object is returned then
Use following
*/
$json = '{
"authenticationResultCode": "ValidCredentials",
"brandLogoUri": "http://dev.virtualearth.net/Branding/logo_powered_by.png",
"copyright": "Copyright © 2019 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
"resourceSets": [
{
  "estimatedTotal": 1,
  "resources": [
    {
      "__type": "Location:http://schemas.microsoft.com/search/local/ws/rest/v1",
      "bbox": [
        40.75594078242932,
        -74.0022632570927,
        40.76366621757067,
        -73.98866508290732
      ],
      "name": "471 W 42nd St, New York, NY 10036",
      "point": {
        "type": "Point",
        "coordinates": [
          40.7598035,
          -73.99546417
        ]
      },
      "address": {
        "addressLine": "471 W 42nd St",
        "adminDistrict": "NY",
        "adminDistrict2": "New York Co.",
        "countryRegion": "United States",
        "formattedAddress": "471 W 42nd St, New York, NY 10036",
        "intersection": {
          "baseStreet": "W 42nd St",
          "secondaryStreet1": "10th Ave",
          "intersectionType": "Near",
          "displayName": "W 42nd St and 10th Ave"
        },
        "locality": "New York",
        "postalCode": "10036"
      },
      "confidence": "High",
      "entityType": "Address",
      "geocodePoints": [
        {
          "type": "Point",
          "coordinates": [
            40.7598035,
            -73.99546417
          ],
          "calculationMethod": "Rooftop",
          "usageTypes": [
            "Display"
          ]
        }
      ],
      "matchCodes": [
        "Good"
      ]
    }
  ]
}
],
"statusCode": 200,
"statusDescription": "OK",
"traceId": "d551494203554f058cd3e2e72582f7b1|HK20271557|7.7.0.0|HK01EAP000001D0"
}';
$JsonData = json_decode($json); 
echo $JsonData->resourceSets[0]->resources[0]->address->addressLine . "<br/>";
echo $JsonData->resourceSets[0]->resources[0]->address->adminDistrict . "<br/>";
  

Комментарии:

1. $jsonData = json_decode($result, true); foreach ($jsonData как $sub_array) { echo $sub_array-> Наборы ресурсов[0]->ресурсы[0]-> адрес-> Адресная строка . «<br/>»; echo $sub_array-> Наборы ресурсов[0]->ресурсы[0]-> адрес-> Административный округ . «<br/>»; }появляется пустая страница

2. Пожалуйста, проверьте, что я создал ответ json в виде массива. Обратите внимание на квадратные скобки и запятую между объектами json.

3. но это происходит из api, как я могу изменить его в вышеуказанный формат

4. Возвращается ли API именно в этом формате. И, пожалуйста, удалите второй синтаксический анализатор из json_decode($result, true) и измените его на json_decode($result).

5. Возвращает ли API один объект json ИЛИ весь, который вы указали в вопросе