PacPac
PacPac

Reputation: 261

Create a new array from a multidimensional array in PHP

I've this sort of multidimensional array in PHP:

Array(
    [0] => Array(
        [continent] => Europe
        [country] => France
        [cities] => Array(
            [0] => Paris
            [1] => Nice
        )
    )
    [1] => Array(
        [continent] => North America
        [country] => Canada
        [cities] => Array(
            [0] => Toronto
            [1] => Ottawa
        )
    )
)

What I'm tryin to do is to list all the cities with the contient and country by creating a new array like this:

Array(
    [0] => Array(
        [city] => Paris
        [continent] => Europe
        [country] => France
    )
    [1] => Array(
        [city] => Nice
        [continent] => Europe
        [country] => France
    )
    ...
)

This is what I've try:

foreach($continents as $continent => $cities) {
    foreach($cities as $city) {
        $arr[] = array('city' => $city, 'continent' => $continent, 'country' => $continent['country']);
    }
}

Thanks for your help.

Upvotes: 1

Views: 344

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46610

Close, you just need to change were you pull the country/continent from:

<?php
$continents = [
    [
        'continent' => 'Europe',
        'country' => 'France',
        'cities' => ['Paris', 'Nice'],
    ],  
    [
        'continent' => 'North America',
        'country' => 'Canada',
        'cities' => ['Toronto', 'Ottawa'],
    ],  
];

$arr = [];
foreach($continents as $key => $value) {
    foreach($value['cities'] as $city) {
        $arr[] = [
            'city' => $city, 
            'continent' => $continents[$key]['continent'], 
            'country' => $continents[$key]['country']
        ];
    }
}

Result:

Array
(
    [0] => Array
        (
            [city] => Paris
            [continent] => Europe
            [country] => France
        )

    [1] => Array
        (
            [city] => Nice
            [continent] => Europe
            [country] => France
        )

    [2] => Array
        (
            [city] => Toronto
            [continent] => North America
            [country] => Canada
        )

    [3] => Array
        (
            [city] => Ottawa
            [continent] => North America
            [country] => Canada
        )

)

https://3v4l.org/suaMW

Upvotes: 1

Related Questions