发出访问嵌套关联数组的元素

时间:2011-02-28 22:07:05

标签: php arrays loops

所以我有一些数据从数据库查询返回,结果数组(得到print_r)看起来像这样(它被分配给一个名为$ locationData的var):

Array
(
    [0] => Array
        (
            [id] => 1
            [location_name] => Cook Minnesota
            [location_lat] => 47.72037
            [location_long] => -90.32667
        )

    [1] => Array
        (
            [id] => 2
            [location_name] => Lake Minnesota
            [location_lat] => 47.18238
            [location_long] => -91.35301
        )

    [2] => Array
        (
            [id] => 3
            [location_name] => St. Louis Minnesota
            [location_lat] => 46.83572
            [location_long] => -91.96299
        )
 )

我有一个foreach循环,需要从每个循环中获取location_name。它看起来像这样:

foreach ($locationData as $location => $value ) {
   echo '<p>name ' . $location['location_name']. '</p>';
}

我99%肯定这应该有效;它基本上和我以前用过十几次的代码相同。但回声并没有返回任何东西 - 甚至不是静态文本(<p>name)。它没有抛出任何错误,如果我尝试执行print_r($ location),我什么也得不到。

有什么想法吗?我确信这很简单。

2 个答案:

答案 0 :(得分:2)

您希望$value['location_name']因为$value代表数组,而$location代表数组的索引:

   echo '<p>name ' . $value['location_name']. '</p>';

答案 1 :(得分:0)

是:

foreach ($locationData as $location => $value ) {
   echo '<p>name ' . $value['location_name']. '</p>';
}