0

I've got this type of multidimensional array in PHP:

Array
(
    [1] => Array
        (
            [0] => Array
                (
                    [Name] => France
                    [Capital] => Paris
                )

            [1] => Array
                (
                    [Name] => Italy
                    [Capital] => Rome
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [Name] => Canada
                    [Capital] => Ottawa
                )

        )

)

How can I loop into it ?

I try from my search on documentation:

foreach ($countries as $country)
{
  foreach ($country["Name"] as $name)
  {
     $capitals = array();
     foreach ($name["Capital"] as $capitals)
     {
       $capitals[] = $capital["Name"];
     }
     print implode(",", $capitals);
  }
}

Desired output should be:

Capital of `France` is `Paris`.
Capital of `Italy` is `Rome`.
Capital of `Canada` is `Ottawa`.

Could you please point me into the right direction ?

Thanks.

5

2 Answers 2

0

You must use two loops to access the lowest subarray, then you can access the values by their keys (Name and Capital).

Code: (Demo)

$array=[
    1=>[
        ['Name'=>'France','Capital'=>'Paris'],
        ['Name'=>'Italy','Capital'=>'Rome']
    ],
    2=>[
        ['Name'=>'Canada','Capital'=>'Ottawa']
    ]
];

foreach($array as $subarray){
    foreach($subarray as $subset){
        echo "Capital of `{$subset['Name']}` is `{$subset['Capital']}`.<br>";
    }
}

Output:

Capital of `France` is `Paris`.
Capital of `Italy` is `Rome`.
Capital of `Canada` is `Ottawa`.
Sign up to request clarification or add additional context in comments.

Comments

0

just update the foreach loop

foreach ($countries as $country)
{
  foreach ($country as $cdata)
  {
     echo "Capital of '".$cdata['Name']."' is '".$cdata['Capital']."'<br/>".
  }
}

3 Comments

This is a late duplicate of my method, therefore it adds no value to the page.
when i posted your answer was not showing my side. thats why i posted. i didn't mean to post duplicate answer
That is understandable, but the fact remains that it is a late duplicate. You should delete it on principle, but I can see that you have received an undermining upvote so now you are less likely to do the right thing. Thanks Upvote Pixies.

Your Answer

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