1

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
    )

)
2
  • 1
    Show some code first. Commented Jan 6, 2017 at 8:45
  • @u_mulder.. I tried many things in for loop but was not working as expected Commented Jan 6, 2017 at 8:56

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Welcome ! If this solution solves your problem, please accept my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.