PHP чтение вложенного массива JSON

#php #arrays #json

#php #массивы #json

Вопрос:

У меня есть вложенный JSON в PHP, я новичок в PHP, и я не могу прочитать вложенный ниже JSON. Вот длинный файл JSON.

 <?php
$nestedjson='{
    "value": [
      {
        "name": "POOL1",
        "id": "/subscriptions/2xxxx-xxxx-xxxx-xxxx/resourcegroups/XXXX/providers/Microsoft.DesktopVirtualization/hostpools/AZREUSLSHP1",
        "type": "Microsoft.DesktopVirtualization/hostpools",
        "location": "eastus",
        "tags": {
          "owner": "Domain",
          "department": "TPW",
          "workLoadType": "WVD",
          "contactName": "testuser1",
          "CostBucket": "bucket1"
        },
        "kind": null,
        "properties": {
          "friendlyName": null,
          "description": "Created through the WVD extension",
          "hostPoolType": "Pooled",
          "personalDesktopAssignmentType": null,
          "applicationGroupReferences": [
            "/subscriptions/xxxx-xxxx-xxxx-xxxx/resourcegroups/XXXX/providers/Microsoft.DesktopVirtualization/applicationgroups/AZREUSLSHP1-DAG",
            "/subscriptions/xxxx-xxxx-xxxx-xxxx/resourcegroups/XXXX/providers/Microsoft.DesktopVirtualization/applicationgroups/AZREUSFINGRP"
          ],
          "customRdpProperty": "",
          "maxSessionLimit": 6,
          "loadBalancerType": "BreadthFirst",
          "validationEnvironment": false,
          "ring": null,
          "registrationInfo": {
            "expirationTime": null,
            "token": null,
            "resetToken": false,
            "registrationTokenOperation": "None"
          },
          "vmTemplate": "{"domain":"XXXX","galleryImageOffer":null,"galleryImagePublisher":null,"galleryImageSKU":null,"imageType":"CustomImage","imageUri":null,"customImageId":"/subscriptions/XXXX/resourceGroups/IMAGEGALLERYRG/providers/Microsoft.Compute/galleries/WVDImageGallery3/images/WVDBaseImageDefinition1","namePrefix":"AZREUSWVD","osDiskType":"StandardSSD_LRS","useManagedDisks":true,"vmSize":{"id":"Standard_B2ms","cores":2,"ram":8},"galleryItemId":null}",
          "preferredAppGroupType": "Desktop",
          "migrationRequest": null,
          "cloudPcResource": false,
          "startVMOnConnect": false,
          "ssoadfsAuthority": null,
          "ssoClientId": null,
          "ssoClientSecretKeyVaultPath": null,
          "ssoSecretType": null,
          "objectId": "3a5db190-342d-441e-9798-667079784cbf"
        }
      },
      {
        "name": "POOL2",
        "id": "/subscriptions/xxxx-xxxx-xxxx-xxxx/resourcegroups/XXXX/providers/Microsoft.DesktopVirtualization/hostpools/AZREUSLSHP2",
        "type": "Microsoft.DesktopVirtualization/hostpools",
        "location": "eastus",
        "tags": {
         "owner": "Domain",
          "department": "TPW",
          "workLoadType": "WVD",
          "contactName": "testuser2",
          "CostBucket": "bucket2"
        },
        "kind": null,
        "properties": {
          "friendlyName": null,
          "description": "Created through the WVD extension",
          "hostPoolType": "Personal",
          "personalDesktopAssignmentType": "Direct",
          "applicationGroupReferences": [
            "/subscriptions/xxxx-xxxx-xxxx-xxxx/resourcegroups/XXXX/providers/Microsoft.DesktopVirtualization/applicationgroups/AZREUSLSHP2-DAG"
          ],
          "customRdpProperty": "",
          "maxSessionLimit": 999999,
          "loadBalancerType": "Persistent",
          "validationEnvironment": false,
          "ring": null,
          "registrationInfo": {
            "expirationTime": null,
            "token": null,
            "resetToken": false,
            "registrationTokenOperation": "None"
          },
          "vmTemplate": "{"domain":"domain.com","galleryImageOffer":"Windows-10","galleryImagePublisher":"microsoftwindowsdesktop","galleryImageSKU":"19h2-ent-g2","imageType":"Gallery","imageUri":null,"customImageId":null,"namePrefix":"AZREUSWVDP","osDiskType":"StandardSSD_LRS","useManagedDisks":true,"vmSize":{"id":"Standard_B2s","cores":2,"ram":4},"galleryItemId":"microsoftwindowsdesktop.windows-1019h2-ent-g2"}",
          "preferredAppGroupType": "Desktop",
          "migrationRequest": null,
          "cloudPcResource": false,
          "startVMOnConnect": false,
          "ssoadfsAuthority": null,
          "ssoClientId": null,
          "ssoClientSecretKeyVaultPath": null,
          "ssoSecretType": null,
          "objectId": "d187b18a-baa7-4e59-97ad-f84a1f50186e"
        }
      },
      {
        "name": "POOL3",
        "id": "/subscriptions/xxxx-xxxx-xxxx-xxxx/resourcegroups/AZREUSLSWVDREFRG/providers/Microsoft.DesktopVirtualization/hostpools/ReferenceHostPool",
        "type": "Microsoft.DesktopVirtualization/hostpools",
        "location": "eastus",
        "tags": null,
        "kind": null,
        "properties": {
          "friendlyName": null,
          "description": null,
          "hostPoolType": "Pooled",
          "personalDesktopAssignmentType": null,
          "applicationGroupReferences": [
            "/subscriptions/xxxx-xxxx-xxxx-xxxx/resourcegroups/AZREUSLSWVDREFRG/providers/Microsoft.DesktopVirtualization/applicationgroups/RefAppGroup"
          ],
          "customRdpProperty": "",
          "maxSessionLimit": 5,
          "loadBalancerType": "DepthFirst",
          "validationEnvironment": false,
          "ring": null,
          "registrationInfo": {
            "expirationTime": null,
            "token": null,
            "resetToken": false,
            "registrationTokenOperation": "None"
          },
          "vmTemplate": null,
          "preferredAppGroupType": "Desktop",
          "migrationRequest": null,
          "cloudPcResource": false,
          "startVMOnConnect": false,
          "ssoadfsAuthority": null,
          "ssoClientId": null,
          "ssoClientSecretKeyVaultPath": null,
          "ssoSecretType": null,
          "objectId": "1f06e1c3-669e-4227-bb7c-386b634c6c30"
        }
      }
    ],
    "nextLink": null
  }'
 

Я хотел бы прочитать и распечатать значения «hostPoolType» из приведенного выше JSON, я попробовал приведенный ниже код, он не сработал.

 $arr = json_decode($nestedjson, true);

$hostpooltype = $arr['properties']['hostPoolType'];

//print_r($hostpooltype);

foreach($hostpooltype as $item)
{
    echo $item;
    echo '<br>';
}
?>
 

Он не возвращает правильный результат. Может кто-нибудь, пожалуйста, помочь здесь?

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

1. Разве это не должно быть $arr['value'][0]['properties']['hostPoolType'] ?

2. Да, вы правы, однако я хотел бы также прочитать значения массива [1] и [2] . Я думаю, мне нужно найти длину массива и запустить цикл for?

3. Итак, если вам также нужны значения из 1-2, вам нужно перебрать их в цикле. Вы просто не можете игнорировать один ключ и ожидать, что он повторится для вас…

Ответ №1:

вы должны запустить цикл для каждого ключа значения массива json. используйте это.

 <?php
$arr = json_decode($nestedjson, true);
foreach ($arr['value'] as $newArr){
    echo $newArr['properties']['hostPoolType'];
    echo '<br>';
}
?>
 

Ответ №2:

Я нашел решение здесь.

 $arr = json_decode($nestedjson, true);
$hostpooltype = array();
$names = array();
foreach ($arr['value'] as $newArr)
{

  $hostpooltype[] = $newArr['properties']['hostPoolType'];
  $names[] = $newArr ['name'];
}
// Print the values of the A
foreach($hostpooltype as $value){
  echo $value . "<br>";
}
 

Ответ №3:

Попробуйте использовать array_walk функцию:

 $arr = json_decode($nestedjson);

function recursiveWalk($value, $key)
{
    if (is_array($value)) {
        array_walk($value, "recursiveWalk");
    }
    if (is_object($value)) {
        echo "{$value->properties->hostPoolType}<br>";
    }
}
array_walk($arr, "recursiveWalk");