Пример моего массива
$options = array( array("brand" => "Puma","code" => "p01","name" => "Puma One"), array("brand" => "Puma","code" => "p02","name" => "Puma Two"), array("brand" => "Puma","code" => "p03","name" => "Puma Three"), array("brand" => "Nike","code" => "n01","name" => "Nike One"), array("brand" => "Nike","code" => "n02","name" => "Nike Two"), array("brand" => "Nike","code" => "n03","name" => "Nike Three"), array("brand" => "Nike","code" => "n04","name" => "Nike Four"), array("brand" => "Adidas","code" => "a01","name" => "Adidas One"), array("brand" => "Adidas","code" => "a02","name" => "Adidas Two"), array("brand" => "Adidas","code" => "a03","name" => "Adidas Three"), array("brand" => "Adidas","code" => "a04","name" => "Adidas Four"), array("brand" => "Adidas","code" => "a05","name" => "Adidas Five"), array("brand" => "Adidas","code" => "a06","name" => "Adidas Six") );
Как сгенерировать этот массив
<select name="products" id="products"> <optgroup label="Puma"> <option value="p01">Puma One</option> <option value="p02">Puma Two</option> <option value="p03">Puma Three</option> </optgroup> ....... <optgroup label="Adidas"> <option value="a01">Adidas One</option> <option value="a02">Adidas Two</option> <option value="a03">Adidas Three</option> ....... </optgroup> </select>
Или вы можете предложить лучший массив в соответствии с моим вариантом выбора. Дай мне знать.
Вы можете создать еще один массив под маркой:
$newOptions = array(); foreach ($options as $option) { $brand = $option['brand']; $code = $option['code']; $name = $option['name']; $newOptions[$brand][$code] = $name; }
Это создаст такой массив:
$newOptions = array( 'Puma' => array('p01' => 'Puma One', 'p02' => 'Puma Two'), 'Nike' => array('n01' => 'Nike One', 'n02' => 'Nike Two'), ... );
Если вы можете напрямую форматировать массив таким образом, вы можете пропустить первый шаг.
Затем перейдите по этому новому массиву и выведите параметры:
foreach ($newOptions as $brand => $list) { echo "<optgroup label=\"$brand\">\n"; foreach ($list as $code => $name) echo "<option value=\"$code\">$name</option>\n"; echo "</optgroup>\n"; }