Php 生成<;选择>;从多维数组

Php 生成<;选择>;从多维数组,php,Php,我有一个具有以下结构的多维数组: [ { id: "2", optgroup: "Size Type A", valor: "40" }, { id: "1", optgroup: "Size Type B", valor: "L" }, { id: "3", optgroup: "Size Type B", va

我有一个具有以下结构的多维数组:

[
    {
        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"
    }
]
我的挑战是使用“optgroud”键创建一个带有optgroup的选择列表,以便按顺序排列项目

像这样:

<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>

40
41
L
特大号
但是我找不到一个方法来做这件事。 任何想法!非常感谢。

试试这个:

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