简体   繁体   中英

php foreach loop multidimensional array having issues

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

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/>";
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM