2011-03-14 23 views
1

嘿傢伙, 我想我失去了我的想法。php:獲取數組值而不需要迭代它?

print_r($location);列出了一些地理數據。

array (
    'geoplugin_city' => 'My City', 
    'geoplugin_region' => 'My Region', 
    'geoplugin_areaCode' => '0', 
    'geoplugin_dmaCode' => '0', 
    'geoplugin_countryCode' => 'XY', 
    'geopl ... 

當我用foreach循環遍歷它時,我可以打印每一行。 但是,不應該有可能從數組中獲取特定值嗎?

like print $location[g4];應該打印countryCode不應該嗎?謝謝!

+0

是,我想你可能有! – 2011-03-14 16:01:48

回答

5
echo $location['geoplugin_countryCode']; 
0

是的,你可以通過鍵獲得一個特定的值。您案例中的密鑰是geoplugin_字符串。

要獲取國家代碼:

// XY 
$location['geoplugin_countryCode']; 
0
$location['geoplugin_countryCode']; 

將訪問的國家代碼

0

哪裏 「G4」 從何而來?你的意思是「4」嗎?

如果你有一個正常的數字索引數組,那麼,是的,你可以寫​​3210。但是,您有一個關聯數組,因此編寫$location['geoplugin_countryCode']

0

有您使用的關聯數組,它是與用戶的陣列限定鍵:值對(類似於在Python字典和哈希表上C#)

可以訪問只是使用密鑰的元素(在這種情況下geoplugin_city或geoplugin_region)

使用標準陣列語法:

$arrayValue = $array[key];  //read 
$array[key] = $newArrayValue; //write 

例如:

$location['geoplugin_city']; or $location['geoplugin_region']; 

如果沒有語言,熟悉PHP數組,你可以在這裏看看:

http://php.net/manual/en/language.types.array.php

有關數組操作更好地瞭解用PHP來看看的:

http://www.php.net/manual/en/ref.array.php