1

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.

1 Answer 1

1

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

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

Comments

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.