2014-10-18 169 views
0

數組我有我的數組中的PHP是這樣的:呼叫在PHP

$countryList = array (
    array(// Asia 
     continent => 'Asia', 
     country => array('Japan', 'China') 
    ), 
    array(// Europe 
     continent => 'Europe', 
     country => array('Spain', 'France', 'Italy') 
    ) 
); 

我怎樣才能把這個陣列($countryList)要問什麼是country的值,如果continent是「亞洲」?

我想有這樣的:

$country = 'Japan, China'; 

非常感謝。

+0

'foreach'循環。 – Cheery 2014-10-18 20:30:28

+1

你可以這樣做,以便數組的基礎索引是大陸名稱。 E.'G. $ countryList = array('europe'=> array('Spain','France'),'asia'=> array());會更容易得到其他數據。 – Jhecht 2014-10-18 20:34:05

回答

2
$countryList = array (
    array(// Asia 
     'continent' => 'Asia', 
     'country' => array('Japan', 'China') 
    ), 
    array(// Europe 
     'continent' => 'Europe', 
     'country' => array('Spain', 'France', 'Italy') 
    ) 
); 

$continent = 'Asia'; 

foreach($countryList as $c) 
    if ($c['continent'] == $continent) 
    { 
     echo join(', ', $c['country']); 
     break; 
    } 

但是,使用關聯數組更好也更容易。

$countryList = array (
    'Asia' => array('Japan', 'China'), 
    'Europe' => array('Spain', 'France', 'Italy') 
); 

$continent = 'Asia'; 

echo isset($countryList[$continent]) ? 
     join(', ', $countryList[$continent]) : 
     'No such continent'; 

最後echo具有if .. then ..結構,並檢查與對應的鍵的元素是否陣列中存在的當量。

+0

我在手機上,但會彈出陣列搜索鍵功能的工作? – Jhecht 2014-10-18 20:34:55

+0

@Jhecht nope,那些不是鑰匙。 – Cheery 2014-10-18 20:36:12

+0

數組搜索返回相應的鍵,我的意思是說。自動更正。然後再次,這不會因爲他的數組狀態。 – Jhecht 2014-10-18 20:40:42

-2

可以爆的這樣的陣列

$country = implode(', ', countryList['Asia']); 

問候

+1

鑑於最初的問題,這是行不通的,因爲'亞洲'不是該數組聲明的有效索引。不要將它與陣列解決方案混淆在其他答案中 – Kypros 2014-10-18 20:39:55

+0

對不起,我沒有看到以前的答案,這是更明確的 – 2014-10-18 20:44:30

0

你應該只更改數據的結構化的方式,這樣的事情:

$countryList = array(
    'Asia' => array('Japan, China'), 
    'Europe' => array('Spain', 'France', 'Italy'), 
); 

這樣,而不必搜索陣列,您可以直接訪問它:

$region = 'Europe'; 
$countries = implode(', ', $countryList[$region]); 
echo "Europe countries: {$countries}.";