在PHP中循环使用多维数组,无法正常工作

时间:2017-09-16 00:47:42

标签: php arrays multidimensional-array foreach

我从服务中获得以下数组,但正常的foreach不起作用。这是我的代码:

Array
(
    [record] => Array
        (
            [0] => Array
                (
                    [name] => Jhon
                    [direction] => street 1
                    [last_name] => ops

                )

            ...

        )

)

我的循环是

 foreach ($array as $key) {
        echo "<h1>".$key["name"]."</h1>";
        echo '<pre>'; var_dump($key);
   }

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您需要使用多个foreach

//echo '<pre>';
foreach ( $array as $records ) {
    foreach ($records as $record ) {
        foreach ($record as $key => $value) {
            printf( '%10s: %s', $key, $value );
        }
    }
}
//echo '</pre>';

示例1

$record = [ 'name'=>'Jhon', 'direction'=>'street 1', 'last_name'=>'ops' ];
$records['record'] = $record;
$array[] = $records;


//echo '<pre>';

//print_r( $array );

foreach ( $array as $records ) {
    foreach ($records as $record ) {
        foreach ($record as $key => $value) {
            printf( '%10s: %s%s', $key, $value, PHP_EOL );
        }
    }
}
//echo '</pre>';

示例2

$record = [ 'name'=>'Jhon', 'direction'=>'street 1', 'last_name'=>'ops' ];
$records['record'] = $record;
$array[] = $records;


foreach ( $array as $records ) {
    foreach ($records as $record ) {
        echo 'Name: '. $record['name'] . '<br>';
    }
}