Jump to content

PHP: Get values from associative array


chagos66

Recommended Posts

I'm trying to get some values from a specifc row of an array. My array has this sort of structure:

 



$places = array( 
array("name" => "Cabot Cove", "area" => "12", "lat" => "-11.003", "lon" => "-151.2285", "pop" => "17"),
array("name" => "Smallville", "area" => "32;", "lat" => "-19.910", "lon" => "-50.205", "pop" => "18"),
array("name" => "Gotham City", "area" => "85", "lat" => "-39.9294", "lon" => "-40.199", "pop" => "14"),
array("name" => "Springfield", "area" => "21.6", "lat" => "-43.9534", "lon" => "-24.2118", "pop" => "18"),
);


 

If a variable $city is set to "Gotham CIty", for example the url of the page could be "/cities/script.php?city=Gotham+City",

 

how do I look through the array and get the "lat" and "lon" values for just this one $city from the array?
Link to comment
https://forums.phpfreaks.com/topic/278346-php-get-values-from-associative-array/
Share on other sites

You could run through the array with a loop and then stop if you find the name you need, like so:

foreach($places as $place)
{
  if ($place['name'] == $_GET['city'])
  {
   $info = $place;
  }
}

Another way to do this is, is to create a seperate array which would be an index for the places.

$index_array = array();

foreach ($places as $k => $place)
{
  $index_array[$place['name']] = $k;
}

// $index_array = array(cabot_cove => 0, smallville = 1, gotham city = 2, etch)
if (array_key_exists($_GET['city'], $index_array))
{
  $info = $places[$index_array];
}

Well Davey K beat me to the punch, but I came up with the first one he did:

<?php

$places = array(
array("name" => "Cabot Cove", "area" => "12", "lat" => "-11.003", "lon" => "-151.2285", "pop" => "17"),
array("name" => "Smallville", "area" => "32;", "lat" => "-19.910", "lon" => "-50.205", "pop" => "18"),
array("name" => "Gotham City", "area" => "85", "lat" => "-39.9294", "lon" => "-40.199", "pop" => "14"),
array("name" => "Springfield", "area" => "21.6", "lat" => "-43.9534", "lon" => "-24.2118", "pop" => "18"),
);

foreach($places as $place) {
    if ($place['name'] == "Gotham City") {
        echo 'The latitude and longitude for ' , $place['name'] , ' is ' , 'lat: ' , $place['lat'] , ' lon: ' , $place['lon'] , '<br>';     
    }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.