0

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.

2

2 Answers 2

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

This works for unlimited group names. First i split array to two parts by groups then i print it.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

1 Comment

But "Size Types" are dynamic.. So I can't assume how many Size Types will copulate the array!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.