Skip to content
Advertisement

Populate option tags with data- attributes using a multidimensional array

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>';
}

Advertisement

Answer

The cities are in a sub array so you need to do a second loop within your existing foreach to iterate over the cities.

You can create a new array to capture the individual city names in the sub-loop, and then implode() them in your <option>:

$cityArray = array();
foreach($values['city'] as $cityKey=>$cityValue) {
    $cityArray[] = $cityValue['name'];
}

$scenario .= '<option value="' . $key . ' data-city="'.implode(',',$cityArray).'">' . $key .'</option>';

Here’s a working example: https://3v4l.org/l986m

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement