I have my array in PHP like this:
$countryList = array (
array( // Asia
continent => 'Asia',
country => array('Japan', 'China')
),
array( // Europe
continent => 'Europe',
country => array('Spain', 'France', 'Italy')
)
);
How can I call this array ($countryList
) to ask what is the value of country
if the continent
is 'Asia' ?
I would like to have something like:
$country = 'Japan, China';
Thanks a lot.
$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;
}
But it is better and easier to use associative arrays.
$countryList = array (
'Asia' => array('Japan', 'China'),
'Europe' => array('Spain', 'France', 'Italy')
);
$continent = 'Asia';
echo isset($countryList[$continent]) ?
join(', ', $countryList[$continent]) :
'No such continent';
The last echo
has an equivalent of the if
.. then
.. structure and checks whether the element with corresponding key exists in the array.
You can implode the array of this way
$country = implode(', ', countryList['Asia']);
Greetings
You should just change the way the data is structured, to something like this:
$countryList = array(
'Asia' => array('Japan, China'),
'Europe' => array('Spain', 'France', 'Italy'),
);
That way, instead of having to search the array, you can just access it directly:
$region = 'Europe';
$countries = implode(', ', $countryList[$region]);
echo "Europe countries: {$countries}.";