Home > Back-end >  Build a custom array in Laravel
Build a custom array in Laravel

Time:07-25

I am looping the database to get a list of countries with continents.

array: [
 0 => array: [
   "country" => "BE"
   "continent" => "EU"
 1 => array: [
   "country" => "BG"
   "continent" => "EU"
 ]
...
 ]

From that result, I want to create an array that shows all the continents with the countries inside.

array:[
  0 => array: [
    "continent" => "EU"
    "countries" => [
      "country" => "BE"
      "country" => "BG"
    ]
  ]

CodePudding user response:

Suppose this is your array

 $arr = [
    [
        "country" => "BE",
        "continent" => "EU",
    ],
    [
        "country" => "BG",
        "continent" => "EU",
    ]
];

Then this returns what you expected.

collect($arr)->groupBy('continent')->mapWithKeys(function ($group, $continent) {
    return [
        'continent' => $continent,
        'countries' => $group->pluck('country')->toArray()
    ];
});

enter image description here

CodePudding user response:

If you need just to group countries by continent, simple way to achieve this by mapToGroups() enter image description here

CodePudding user response:

You will need to some how group your results by the continent. One way to do that is to loop over the initial collection and build a new array keyed by the continent.

However, seeing that you are using Laravel just group the collection by the continent.

$countries = [
    ['country' => 'A', 'continent' => 'aa'],
    ['country' => 'B', 'continent' => 'bb'],
    ['country' => 'C', 'continent' => 'aa'],
    ['country' => 'D', 'continent' => 'aa'],
    ['country' => 'E', 'continent' => 'aa'],
    ['country' => 'F', 'continent' => 'bb'],
];

// Because my data is an array I just turn that into a collection.
// But an Eloquent query builder ->get would already return a collection.
$continents = collect($countries)->groupBy('continent');

foreach ($continents as $continent => $items) {
    echo "Countries for " . $continent . "\n";
    foreach ($items as $country) {
        echo $country['country'] . "\n";
    }
}

/**
Output: 
Countries for aa
A
C
D
E
Countries for bb
B
F
**/
  • Related