答案 0 :(得分:1)
<?php
$items = [
[
'id'=> "2",
'optgroup'=> "Size Type A",
'valor'=> "40"
],
[
'id'=> "1",
'optgroup'=> "Size Type B",
'valor'=> "L"
],
[
'id' => "3",
'optgroup' => "Size Type B",
'valor'=> "XL"
],
[
'id' => "4",
'optgroup' => "Size Type A",
'valor' => "41"
]
];
$groups = [];
foreach($items as $i)
{
$groups[$i['optgroup']]=[];
}
foreach($items as $i)
{
array_push($groups[$i['optgroup']], $i);
}
echo '<select>';
foreach($groups as $key=>$g)
{
echo '<optgroup label="'.$key.'">';
foreach($g as $gg)
{
echo '<option>'.$gg['valor'].'</option>';
}
echo '</optgroup>';
}
echo '</select>';
这适用于无限制的组名。首先,我将数组分成两个部分然后打印出来。
答案 1 :(得分:0)
试试这个:
<?php
$array = [
[
"id" => 2,
"optgroup"=> "Size Type A",
"valor"=> 40
],
[
"id"=> 1,
"optgroup"=> "Size Type B",
"valor"=> "L"
],
[
"id"=> 3,
"optgroup"=> "Size Type B",
"valor"=> "XL"
],
[
"id"=> 4,
"optgroup"=> "Size Type A",
"valor"=> 41
]
];
$optgroups = [];
foreach ($array as $item){
$optgroups[]=$item["optgroup"];
}
$optgroups = array_unique($optgroups);
?>
<select>
<?php foreach ($optgroups as $optgroup){
echo '<optgroup label="'.$optgroup.'">';
foreach ($array as $item){
if($item["optgroup"]==$optgroup){
echo '<option>'.$item["valor"].'</option>';
}
}
echo '</optgroup>';
} ?>
</select>