1

I tried to use ORM to find list of provinces and their cities.

the result is same as this list:

"provinces": [
    {
        "name": "Prov.1",
        "Cities": {
            "name": "City.1"
        }
    },
    {
        "name": "Prov.1",
        "Cities": {
            "name": "City.2"
        }
    },
]

what is expected:

"provinces": [
    {
        "name": "Prov.1",
        "Cities": [
            {
                "name": "City.1"
            },
            {
                "name": "City.2"
            }
        ]
    },
]

used ORM:

Provinces::find('all', [
    'with' => ['Cities']
]);
Ramin Firooz
  • 506
  • 8
  • 25

1 Answers1

1

Something like

$array = [];
foreach($provinces as $province){
    $key = $province['name'];
    if(!isset($array[$key])){
       $array[$key] = [
         'name' => $province['name'], 
         'Cities' => [
              [ 'name' => $province['Cities']['name']];
          ]
       ];
    }else{
       $array[$key]['Cities'][] = ['name' => $province['Cities']['name']];
    }
}

 //strip keys
$array = array_values($array);

Because you don't have an actual PHP array posted I'm just guessing at what it should be.

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38