2

I'm having problems getting values in my multidimensional arrays

Array
(
    [0] => Array
        (
            [name] => Brandow & Johnston, Inc.
            [lat] => 34.051405
            [lng] => -118.255576
        )

    [1] => Array
        (
            [name] => Industry Metrolink Train Station
            [lat] => 34.00848564346
            [lng] => -117.84509444967
        )

    [2] => Array
        (
            [name] => The Back Abbey
            [lat] => 34.095161
            [lng] => -117.720638
        )

    [3] => Array
        (
            [name] => Eureka! Burger Claremont
            [lat] => 34.094572563643
            [lng] => -117.72184828904
        )

)

Lets say I have an array such above

And I'm using a foreach loop such as below

foreach($_SESSION['array'] as $value){

    foreach($valueas $key_location=> $value_location){

        if($key_location = "name"){$fsq_name = $value_location;}
        $fsq_lat = $value_location["lat"];
        $fsq_lng = $value_location["lng"];



        echo "<i>".$fsq_lat."</i><br/>";

        }

    }

I've tried using the if statement, or using $value_location["lat"]; but its not producing the correct values.

If I do if($key_location === "lng"){$fsq_lng = $value_location;} with three equal signs, it'll give me errors for a few iterations and then produce the lng results. if I just do one equal sign and echo it out, it'll give me the name key as well.

Am I missing something?

Thanks

1
  • First of all, foreach($valueas appears to be missing a space. Second, are you aware that if($key_location = name) sets the variable $key_location to "name" and then evaluates to true? Use == to check equality or === to check identity (similar to equality but stronger). Commented Mar 22, 2012 at 2:28

2 Answers 2

6

You don't actually need the inner foreach loop. The outer one is sufficient, since it iterates over arrays. The inner arrays can be accessed by key inside the outer foreach.

foreach($_SESSION['array'] as $value){
  $fsq_name = $value["name"];
  $fsq_lat = $value["lat"];
  $fsq_lng = $value["lng"];

  echo "<i>".$fsq_lat."</i><br/>";

  // Actually none of the above assignments are necessary
  // you can just:
  echo "<i>".$value["lat"]."</i><br/>";
}
0
0

Maybe refactor a bit?

foreach($_SESSION['array'] as $value)
{
    // pull the lat and lng values from the value
    $fsq_lat = $value["lat"];
    $fsq_lng = $value["lng"];
    $fsq_name = $value["name"];

echo "<i>".$fsq_lat."</i><br/>";


}// foreach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.