Loop through multidimensional json array using PHP

Today my requirement was to loop through a multidimentional Json. It means i have N numbers of nodes and sub-nodes in my json. 

I have to read all the key and value into this and perform search operations. After spending hours in Google. Finally i found the solution of it. 

Before moving a head i want to show you the sample of my Json that i need to read . My Json is something like this:

$json = '{
 "masterImportTemplateValues": {
  "masterRider": {
   "name": "Mahesh Nagaraj",
   "type": "{{translationKey}}",
   "phoneNumber": "1234567890",
   "teams": "KOR,HSR",
   "pjpData": {
    "revenueGenerated": "{{translationKey}} 120000",
    "skusSoldCount": "50",
    "salesCategories": "SOAPS, OIL, JAMS"
   },
   "competency": {
    "joiningDate": "13/05/2018",
    "experience": "10",
    "rating": "4.5",
    "skills": "skill1, skill2"
   },
   "bioData": {
    "dateOfBirth": "13/05/1980"
   },
   "startLocation": "Ford Cauvery, 8th Block, Koramangala",
   "endLocation": "Ford Cauvery, 8th Block, Koramangala",
   "riderId": "BLR001",
   "riderCode": "BLR001",
   "workingDays": "08:00AM-05:00PM",
   "breaks": "12:00PM-01:00PM",
   "startLat": "12.94509",
   "startLng": "77.619343",
   "timeSlot": {
    "endLat": "12.94509",
    "endLng": "77.619343",
    "minTask": "0",
    "maxTask": "99"
   }
  },
  "masterLocation": {
   "name": "Bangalore Warehouse",
   "type": "{{translationKey}}",
   "teams": "KOR,HSR",
   "tat": "30 {{translationKey}}",
   "address": {
    "placeName": "Central Warehouse",
    "address": "23rd Cross, 4th Main, Block 4, Koramangala, Bengaluru",
    "locality": "Koramangala",
    "city": "Bengaluru",
    "state": "Karnataka",
    "pincode": "560034",
    "country": "Country Code. Ex: IN for India"
   },
   "locationId": "BLR_WH",
   "locationCode": "BLR_WH",
   "latitude": "12.94509",
   "longitude": "77.619343",
   "operatingSlots": "08:00AM-05:00PM, 06:00PM-09:00PM",
   "contactId": "BLR001",
   "skills": "skill1, skill2"
  },
  "masterShift": {
   "id": "Shift_001",
   "code": "Shift_001",
   "name": "Morning Shift",
   "teamId": "HSR",
   "workingDays": "08:00AM-05:00PM",
   "breaks": "12:00PM-01:00PM, 06:00PM-08:00PM",
   "startLocation": "Ford Cauvery, 8th Block, Koramangala",
   "endLocation": "Ford Cauvery, 8th Block, Koramangala",
   "startLat": "12.94509",
   "startLng": "77.619343",
   "endLat": "12.94509",
   "endLng": "77.619343"
  },
  "masterOutlet": {
   "outletId": "BLR_1",
   "outletCode": "BLR_1",
   "name": "Bangalore-1",
   "team": "BLR",
   "timeSlots": "08:00AM-05:00PM, 06:00PM-09:00PM",
   "locationId": "BLR_1",
   "currentPjpName": "PJP Name",
   "customFieldsValue": "{{translationKey}}",
   "transactionDuration": "30 {{translationKey}}",
   "keepRemove": "Keep, Remove",
   "booleanValue": "Yes, No",
   "revenueGenerated": 0,
   "riderId": "rider1",
   "skuSales": "0",
   "booleanValues": {
     "keep": "Keep",
     "remove": "Remove"
   },
   "planningDuration": "1 {week(s)}",
   "repeatCount": "1",
   "currentPjpDay": "MONDAY",
   "currentPjpWeek": "WEEK1",
   "frozenBeat": "Beat1",
   "mandatoryDays": "Monday, Tuesday"
  }
 }
}';




Now below is my code to read the key and value from the above type of json structure:

class RecursiveArrayOnlyIterator extends RecursiveArrayIterator {
  public function hasChildren() {
    return is_array($this->current());
  }
}

function traverseStructure($iterator) 
{  
    while ( $iterator -> valid() ) { 

        if ( $iterator -> hasChildren() ) { 
        
            traverseStructure($iterator -> getChildren()); 
            
        } 
        else {
   echo "Key: " .$iterator ->key().", "."Value: " . $iterator -> current()."<br>";
        } 

        $iterator -> next(); 
    } 
}

$iterator = new RecursiveArrayIterator(json_decode($json, true)); 
iterator_apply($iterator, 'traverseStructure', array($iterator));

When you run the above code in brower it will output all the keys and values from json like below:

Loop through the json or array using PHP

NOTE: The above function will work only with PHP 5 >=5.1.0, PHP 7


Please don't forgot to leave a comment if you like this post. Chears :) 

Happy Coding..


Post a Comment

Previous Post Next Post