val-6ren">
gpt4 book ai didi

php - Laravel - 填充选择 optgroup 下拉列表,按名称对记录进行分组

转载 作者:太空宇宙 更新时间:2023-11-03 11:56:39 25 4
gpt4 key购买 nike

我正在尝试填充 select Laravel 中的下拉菜单以显示产品的属性。

<select>
@foreach($attributes as $key=>$attr)
<optgroup label="{{$attr->name}}">
<option value="{{$attr->value}}">{{$attr->value}}</option>
</optgroup>
@endforeach
</select>

当用户存储他可能存储的属性的数据时Color: Red with id=1Color: Blue with id=2 .

用于获取数据的查询是:

$attributes = Attribute::orderBy('name', 'ASC')->get();

不过,我需要根据名称查找类似的记录,例如 Color . select下拉列表应列出 $attr->name曾经在 <optgroup label>$attr->value应在 <option value> 中重复.

我试图改变查询并使用 groupBy但这不会像预期的那样工作。查询将只返回任何记录的第一个实例,其余的将被忽略。

$attributes = Attribute::orderBy('name', 'ASC')->groupBy('name')->get();

我该如何解决这个问题?提前谢谢你。

最佳答案

我会将所有属性放入一个多维数组中,然后迭代以生成选择。

// Fetch all attributes
$results = Attribute::orderBy('name', 'ASC')->get();
$attributes = array();
/**
* Group results into a multidimensional array like:
* [color]
* [red]
* [white]
* [shape]
* [circle]
* [square]
*/
foreach ( $results as $v ) {
if ( !isset($attributes[$v->name]) ) {
$attributes[$v->name] = array();
}
$attributes[$v->name][$v->value] = $v->value;
}
// Spit out the select/option groups
?>
<select>
@foreach ( $attributes as $key => $attr )
<optgroup label="{{$key}}">
@foreach ( $attr as $values )
<option value="{{$value}}">{{$value}}</option>
@endforeach
</optgroup>
@endforeach
</select>

关于php - Laravel - 填充选择 optgroup 下拉列表,按名称对记录进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32188712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com