Search code examples
javascriptphparraysjsonarray-merge

Merging PHP arrays and nest relations


I have two arrays in PHP that I need to pass in to a JS script. The PHP arrays are locations and rooms as follows:

var_dump($locations)

Array ( [0] => Array 
               ( [id] => 1
                 [name] => "London"  )
        [1] => Array 
               ( [id] => 2
                 [name] => "Manchester"  )
      )

var_dump($rooms)

Array ( [0] => Array 
               ( [id] => 1
                 [locationId] => "1"
                 [name] => "Lon Room 1"  )
        [1] => Array 
               ( [id] => 2
                 [locationId] => "1"
                 [name] => "Lon Room 2"  )
        [2] => Array 
               ( [id] => 3
                 [locationId] => "1"
                 [name] => "Lon Room 3"  )
        [3] => Array 
               ( [id] => 4
                 [locationId] => "2"
                 [name] => "Man Room 1"  )
        [4] => Array 
               ( [id] => 5
                 [locationId] => "2"
                 [name] => "Man Room 2"  )
      )

I need to merge the rooms array in to the locations array grouping rooms under their appropriate locations so that I am able to spit out the following syntax to a JS plugin called DailyPlot Scheduler.

{ name: "London", id: "1", children:[
         { name : "Lon Room 1", id : "1" },
         { name : "Lon Room 2", id : "2" },
         { name : "Lon Room 3", id : "3" }
         ] 
 },
 { name: "Manchester", id: "2", children:[
         { name : "Man Room 1", id : "1" },
         { name : "Man Room 2", id : "2" }
         ] 
 }

I'm learning a few things here and there as part of my apprenticeship but am not good enough to wrap my head around this by myself just yet haha sorry and thank you!


Solution

  • If you create an array that's indexed by location id, then you can use the index to add children for a specified location:

    $locations_by_id = [];
    
    foreach($locations as $location) {
        $location['children'] = []; //initialize children to an empty array
        $locations_by_id[$location['id']] = $location;
    }
    
    foreach($rooms as $room) {    
        //add room to location
        $locations_by_id[$room['locationId']]['children'][] = $room;
    }
    
    $locations = array_values($locations_by_id); //removes the id index
    
    print json_encode($locations);