I have a json file that looks something like this:
{
"world": {
"france": {
"city": {
"city_1": {
"name": "paris",
"titre": "lorem ipsum"
},
"city_2": {
"name": "marseille",
"titre": "dolor sit amet"
}
}
},
"usa": {
"city": {
"city_1": {
"name": "new york",
"titre": "lorem ipsum"
},
"city_2": {
"name": "los angeles",
"titre": "lorem ipsum"
},
"city_3": {
"name": "portland",
"titre": "lorem ipsum"
}
}
}
}
}
I would like to display a set of option tags with countries as text and some additional attribute declarations like this:
<option value="france" data-city="paris,marseille">france</option>
<option value="usa" data-city="new york,los angeles,portland">usa</option>
I tried something like this to display the countries, but I can't display the list of cities.
foreach ($data['world'] as $key => $value)
{
$scenario .= '<option value="' . $key . ' data-city="">' . $key .'</option>';
}
My Answer:
To populate the option tags with the countries and their cities, you can modify your loop to include the cities as data attributes. Here's an example of how you can achieve this:
php
$options = '';
foreach ($data['world'] as $country => $countryData) {
$cities = array_keys($countryData['city']);
$cityList = implode(',', $cities);
$options .= '';
}
echo $options;
This code will loop through each country in the JSON data, extract the list of cities for that country, and then populate the option tag with the country name as text and the list of cities as a data attribute.
Rate this post
5 of 5 based on 5191 votesComments