2014-10-18 159 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}.";