EmmyS
EmmyS

Reputation: 12138

Issue accessing elements of nested associative array

So I have some data that's coming back from a database query, and the resulting array (gotten with print_r) looks like this (it's assigned to a var called $locationData):

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
        )
 )

I have a foreach loop that needs to grab the location_name from each. It looks like this:

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

I'm 99% certain this should work; it's basically the same code I've used a dozen times before. But the echo is not returning anything - not even the static text (<p>name). It's not throwing any errors, and if I try to do a print_r($location), I get nothing.

Any ideas? I'm sure it's something really simple.

Upvotes: 1

Views: 473

Answers (2)

Gelmir
Gelmir

Reputation: 1857

It is:

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

Upvotes: 0

BoltClock
BoltClock

Reputation: 724292

You want $value['location_name'] because $value represents the arrays while $location represents the indexes of the arrays:

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

Upvotes: 2

Related Questions