<optgroup>

时间:2018-12-05 11:24:45

标签: php html arrays loops

我有一个数组

$this->getprevioussprint = Array

(     [0] =>数组         (             [release_name] => Relese1             [sprint_name] => Sprint1             [sprint_id] => 1         )

[1] => Array
    (
        [release_name] => Relese1
        [sprint_name] => Sprint2
        [sprint_id] => 2
    )

[2] => Array
    (
        [release_name] => v2
        [sprint_name] => Sprint1
        [sprint_id] => 3
    )

我在与组相关的选项中有一个Foreach循环, 所以我尝试了

<select class="col-md-2">
    <?php foreach ($this->getprevioussprint as $key =>$pSprint):
    $prev=$pSprint['release_name'];
    ?>
    <optgroup label="<?php echo  $pSprint['release_name'] ;  ?>">
        <option value=""><?php echo $pSprint['sprint_name'] ?></option>
    </optgroup>
</select>

但是我得到了输出

 <select>
        <optgroup label="release_name">
            <option value="1">Sprint1</option>
        </optgroup>
        <optgroup label="Relese1">
            <option value="2">Sprint2</option>
        </optgroup> 
 <optgroup label="V2">
            <option value="3">Sprint1</option>
        </optgroup> 
    </select>

预期产量

 <select>
        <optgroup label="Relese1">
            <option value="1">Sprint1</option>
            <option value="2">Sprint2</option>
        </optgroup> 
 <optgroup label="v2">
            <option value="3">sprint1</option>

        </optgroup> 
    </select>

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

首先,您需要对数组进行分组。具有相同release_name的均值数组放在一个数组中。因此,使用

$newArr = [];
foreach ($_this->getprevioussprint as $item){
    $newArr[$item['release_name']][] = $item;
}

然后循环遍历新数组

<select class="col-md-2">
    <?php foreach ($newArr as $key=>$item): ?>
    <optgroup label="<?= $key ?>">
        <?php foreach ($item as $key=>$pSprint): ?>
        <option value=""><?= $pSprint['sprint_name'] ?></option>
        <?php endforeach ?>
    </optgroup>
    <?php endforeach ?>
</select>

答案 1 :(得分:0)

首先需要使用发布名称对数组进行分组:

echo '<select class="col-md-2">';

    foreach (group_by_release_name($this->getprevioussprint) as $key => $val):

        echo '<optgroup label="'.$key.'">';

        foreach($val as $k => $v):

            echo '<option value="'.$v['sprint_id'].'">'.$v['sprint_name'].'</option>';

        endforeach;

        echo '</optgroup>';

    endforeach;

echo '</select>';

function group_by_release_name($arr){

    $result = [];

    $current_release_name = '';

    foreach($arr as $k => $v){
        $current_release_name = $v['release_name'];

        unset($v['release_name']);

        $result[$current_release_name][] = $v;
    }

    return $result;
}