I have an array of States/Cities where each element has a $cities['parent']
key (the value is 0
for States, and > 0
or Cities, like this:
$cities = array(
'1' => array(
'id' => '1',
'parent' => '0',
'name' => 'California',
),
'2' => array(
'id' => '2',
'parent' => '0',
'name' => 'Texas',
),
'3' => array(
'id' => '3',
'parent' => '0',
'name' => 'Florida',
),
'4' => array(
'id' => '4',
'parent' => '1',
'name' => 'Los Angeles',
),
'5' => array(
'id' => '5',
'parent' => '1',
'name' => 'San Francisco',
),
'6' => array(
'id' => '6',
'parent' => '1',
'name' => 'Sacramento',
),
'7' => array(
'id' => '7',
'parent' => '2',
'name' => 'Houston',
),
'8' => array(
'id' => '8',
'parent' => '2',
'name' => 'Dallas',
),
'9' => array(
'id' => '9',
'parent' => '3',
'name' => 'Miami',
),
'10' => array(
'id' => '10',
'parent' => '3',
'name' => 'Orlando',
),
)
I also have a recursive function to generate <select>
options, like this:
function citiesSelect($ancestor, $array, $level, $selected = 0) {
$has_children = false;
foreach($array as $key => $value) {
if ($value['parent'] == $ancestor) {
if ($has_children === false && $ancestor) {
$has_children = true;
}
?>
<option value="<?php echo $value['id'] ?>" <?php echo ($value['id']) == $selected ? ' selected' : ''; ?>><?php echo $value['name']; ?></option>
<?php
citiesSelect($key, $array, $level, $selected);
}
}
}
And I recall with this:
<select>
<?php citiesSelect(0, $cities, 0); ?>
</select>
This is fine (here is a working fiddle: http://phpfiddle.org/main/code/uiax-n03q) but here comes a problem: I'd like to put States in an <optroup>
so they are not selectable, and resulting in a <select>
like this:
<select>
<optgroup label="California">
<option value="4">Los Angeles</option>
<option value="5">San Francisco</option>
<option value="6">Sacramento</option>
</optgroup>
<optgroup label="Texas">
<option value="7">Houston</option>
<option value="8">Dallas</option>
</optgroup>
<optgroup label="Florida">
<option value="9">Miami</option>
<option value="10">Orlando</option>
</optgroup>
</select>
That's fine: how to achieve this?
Thanks in advance
EDIT: thanks to answers that suggest to split into 2 arrays, but sorry I can't modify it! The array yet serves successfully another classic menu (<ul>...</ul>
) and anyway I could have a third level like:
'11' => array(
'id' => '11',
'parent' => '4',
'name' => 'Hollywood',
),
'12' => array(
'id' => '12',
'parent' => '4',
'name' => 'Santa Monica',
)