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.
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`.
just update the foreach loop
foreach ($countries as $country)
{
foreach ($country as $cdata)
{
echo "Capital of '".$cdata['Name']."' is '".$cdata['Capital']."'<br/>".
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.