2

I have a custom model with three fields, i.e id, city and region. How can I remove duplicates from the region column when querying the table? How can I group all the cities under the same region? I have pasted the response from the model below

Array ( [0] => Array

    (   [city] => City 1
        [region] => Region 1
    )

[1] => Array

    (   [city] => City 2
        [region] => Region 1
    )

[2] => Array
    (   [city] => City 3
        [region] => Region 1
    )

[3] => Array
    (
        [city] => City 4
        [region] => Region 1
    )

)

0

1 Answer 1

1

Assume you have the below array:

Array
(
    [0] => Array
        (
            [city] => City 1
            [region] => Region 1
        )

    [1] => Array
        (
            [city] => City 2
            [region] => Region 1
        )

    [2] => Array
        (
            [city] => City 3
            [region] => Region 1
        )

    [3] => Array
        (
            [city] => City 4
            [region] => Region 1
        )

    [4] => Array
        (
            [city] => City 1
            [region] => Region 2
        )

    [5] => Array
        (
            [city] => City 2
            [region] => Region 2
        )

    [6] => Array
        (
            [city] => City 1
            [region] => Region 3
        )

)

You can use the below code to group city by region:

$items = [];
foreach ($collection as $item) {
    $items[$item['region']][] = $item['city'];
}

The result:

Array
(
    [Region 1] => Array
        (
            [0] => City 1
            [1] => City 2
            [2] => City 3
            [3] => City 4
        )

    [Region 2] => Array
        (
            [0] => City 1
            [1] => City 2
        )

    [Region 3] => Array
        (
            [0] => City 1
        )

)
2
  • Thank you. So much
    – Tebby
    Commented Oct 24, 2022 at 17:29
  • Glad to hear that. Cheers!
    – Tu Van
    Commented Oct 24, 2022 at 17:31

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.