I have a multidimensional array with this structure:
[
{
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"
}
]
My challenge is to create a select list with optgroup using "optgroud" key to arrange items in order.
Like this:
<select>
<optgroup label="Size Type A">
<option>40</option>
<option>41</option>
</optgroup>
<optgroup label="Size Type B">
<option>L</option>
<option>XL</option>
</optgroup>
</select>
But I can't find a way to do this. Any idea! Thanks a lot.
try this:
<?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>
<?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>';
This works for unlimited group names. First i split array to two parts by groups then i print it.