如何使用foreach循环显示多维关联数组的值

时间:2017-09-21 11:48:44

标签: php arrays multidimensional-array foreach associative-array

我有一个Multidimensional Associative数组,想要使用foreach循环访问数组中的任何值。

$a = array('Name:' =>'Khan',
       'City:' => 'Dubai',
       'DOB:' => '1992',
       'Father' => array(
           'Father Name:' => 'Jan',
           'Nic:' => '21105-2111336-3'
       ));
foreach($a as $key => $value){
    echo $key.' '.$value.'<br>';
}

我试过这个,但它只访问主阵列,我不知道如何访问内部数据。

1 个答案:

答案 0 :(得分:0)

function array2string($ary, $depht=0)
{
    $output = ""; // string that represents your array
    $prefix = ""; // spaces to print before "key value"
    for ($i = 0; $i < $depht; $i++) // print as many spaces "\t" as how deep we are in the array
    {
        $prefix .= "\t";
    }
    foreach($ary as $key => $value)
    {
         if (is_array($value))
         {
             // if $value is an array print it with this same function
             $output .= array2string($value, $depht+1);
         } else
         {
             // else, simply append "key value"
             $output .= $prefix . $key . ' ' . $value . '<br />';
         }
    }

    return $output;
}

现在这段代码:

$a = array(
            'Name:' =>'Khan',
            'City:' => 'Dubai',
            'DOB:' => '1992',
            'Father' => array(
                                'Father Name:' => 'Jan',
                                'Nic:' => '21105-2111336-3'
                       )
                    );


echo array2string($a);

输出:

Name: Khan
City: Dubai
DOB: 1992
    Father Name: Jan
    Nic: 21105-2111336-3