RecursiveArrayIterator - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of RecursiveArrayIterator.php

  1. <?php
  2.  
  3. $myJsonArray = '[
  4.     {
  5.     "custClass": [
  6.         {
  7.             "code": "50824109d3b1947c9d9390ac5caae0ef",
  8.             "desc": "e1f96b98047adbc39f8baf8f4aa36f41"
  9.         },
  10.         {
  11.             "code": "dab6cc0ed3688f96333d91fd979c5f74",
  12.             "desc": "d0e850f728b2febee79e1e7d1186c126"
  13.         },
  14.         {
  15.             "code": "bc4050f8f891296528ad6a292b615e86",
  16.             "desc": "bee3120e77092d889c3b9e27cbee75bd"
  17.         },
  18.         {
  19.             "code": "f13fc8c35dfe206a641207c6054dd9a0",
  20.             "desc": "32a81cb610805d9255d5f11354177414"
  21.         },
  22.         {
  23.             "code": "2117c346d9b3dfebf18acc8b022326d4",
  24.             "desc": "88a8e85db11976082fed831c4c83838e"
  25.         },
  26.         {
  27.             "code": "95c0674fc0e0434f52a60afce74571d2",
  28.             "desc": "39c4d4bca1578194801f44339998e382"
  29.         },
  30.         {
  31.             "code": "c8ad6f709612d2a91bb9f14c16798338",
  32.             "desc": "6b4c4d5f4ae609742c1b6e62e16f8650"
  33.         }
  34.     ],
  35.     "sourceData": [
  36.         {
  37.             "sourceId": "ff64060a40fc629abf24eb03a863fd55",
  38.             "sourceName": "92aa69979215a2bf6290c9a312c5891f"
  39.         }
  40.     ]
  41. }]';
  42.  
  43. # Convert $myJsonArray into an associative array
  44. $myJsonArray = json_decode($myJsonArray, true);
  45.  
  46. $myIterator = new RecursiveArrayIterator($myJsonArray);
  47. recursiveArray($myIterator);
  48.  
  49. # Use the RecursiveArrayIterator to traverse the $myJsonArray array
  50. function recursiveArray(RecursiveArrayIterator $myIterator)
  51. {
  52.     while ($myIterator->valid()) {
  53.         if ($myIterator->hasChildren()) {
  54.             recursiveArray($myIterator->getChildren());
  55.         } else {
  56.             if ($myIterator->key() === 'desc') {
  57.                 echo $myIterator->current() . PHP_EOL;
  58.             }
  59.         }
  60.         $myIterator->next();
  61.     }
  62. }
  63.  
  64. /**
  65. OUTPUT
  66. e1f96b98047adbc39f8baf8f4aa36f41
  67. d0e850f728b2febee79e1e7d1186c126
  68. bee3120e77092d889c3b9e27cbee75bd
  69. 32a81cb610805d9255d5f11354177414
  70. 88a8e85db11976082fed831c4c83838e
  71. 39c4d4bca1578194801f44339998e382
  72. 6b4c4d5f4ae609742c1b6e62e16f8650
  73.  */
File Description
  • RecursiveArrayIterator
  • PHP Code
  • 06 Oct-2022
  • 1.98 Kb
You can Share it: