使用PHP循环到多维数组

时间:2017-11-10 04:03:11

标签: php arrays

我在PHP中有这种类型的多维数组:

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

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

        )

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

        )

)

我怎样才能进入呢?

我尝试搜索文档:

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

期望的输出应该是:

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

请你指点我正确的方向吗?

感谢。

2 个答案:

答案 0 :(得分:0)

您必须使用两个循环来访问最低的子数组,然后您可以通过其键(NameCapital)来访问这些值。

代码:(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>";
    }
}

输出:

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

答案 1 :(得分:0)

只需更新foreach循环

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