hrishi
hrishi

Reputation: 1656

Assign value from array as key and merge records of same key

I have array like below in PHP (Codeigniter). I want to group them by using country names. So value of country key will become key of outer array

Array
(
    [0] => Array
        (
            [city] => Buenos Aires
            [country] => Argentina
        )

    [1] => Array
        (
            [city] => Adelaide
            [country] => Australia
        )

    [2] => Array
        (
            [city] => Brisbane
            [country] => Australia
        )

    [3] => Array
        (
            [city] => Fremantle
            [country] => Australia
        )

    [4] => Array
        (
            [city] => Melbourne
            [country] => Australia
        )

    [5] => Array
        (
            [city] => Sydney
            [country] => Australia
        )

)

I want to convert it into array like below so country will become key with city list as per country name

Array
(
    [Argentina] => Array
    (
        [0] => Buenos Aires
    )

    [Australia] => Array
    (
        [0] => Adelaide
        [1] => Brisbane
        [2] => Melbourne
        [3] => Sydney
    )

)

Upvotes: 1

Views: 36

Answers (1)

Rahul
Rahul

Reputation: 18557

Here is the code,

$arr = [//your arr];

$result = []; // will be your output

foreach($arr as $k => $v){
   $result[$v['country']][] = $v['city'];
}

I hope this will work

Upvotes: 1

Related Questions