"Puma","code" => "p01","name" => "Puma One"), arra-6ren">
gpt4 book ai didi

php - 如何对相同的数组值进行分组

转载 作者:可可西里 更新时间:2023-11-01 13:12:43 24 4
gpt4 key购买 nike

示例我的数组

$options = array(
array("brand" => "Puma","code" => "p01","name" => "Puma One"),
array("brand" => "Puma","code" => "p02","name" => "Puma Two"),
array("brand" => "Puma","code" => "p03","name" => "Puma Three"),
array("brand" => "Nike","code" => "n01","name" => "Nike One"),
array("brand" => "Nike","code" => "n02","name" => "Nike Two"),
array("brand" => "Nike","code" => "n03","name" => "Nike Three"),
array("brand" => "Nike","code" => "n04","name" => "Nike Four"),
array("brand" => "Adidas","code" => "a01","name" => "Adidas One"),
array("brand" => "Adidas","code" => "a02","name" => "Adidas Two"),
array("brand" => "Adidas","code" => "a03","name" => "Adidas Three"),
array("brand" => "Adidas","code" => "a04","name" => "Adidas Four"),
array("brand" => "Adidas","code" => "a05","name" => "Adidas Five"),
array("brand" => "Adidas","code" => "a06","name" => "Adidas Six")
);

如何生成这个数组

<select name="products" id="products">
<optgroup label="Puma">
<option value="p01">Puma One</option>
<option value="p02">Puma Two</option>
<option value="p03">Puma Three</option>
</optgroup>
.......
<optgroup label="Adidas">
<option value="a01">Adidas One</option>
<option value="a02">Adidas Two</option>
<option value="a03">Adidas Three</option>
.......
</optgroup>
</select>

或者您可以根据我的选择选项输出建议更好的数组。让我知道。

最佳答案

您可以创建另一个以品牌为键的数组:

$newOptions = array();
foreach ($options as $option) {
$brand = $option['brand'];
$code = $option['code'];
$name = $option['name'];

$newOptions[$brand][$code] = $name;
}

这将产生一个像这样的数组:

$newOptions = array(
'Puma' => array('p01' => 'Puma One', 'p02' => 'Puma Two'),
'Nike' => array('n01' => 'Nike One', 'n02' => 'Nike Two'),
...
);

如果你可以像这样直接格式化你的数组,你可以跳过第一步。

然后迭代这个新数组并输出选项:

foreach ($newOptions as $brand => $list) {
echo "<optgroup label=\"$brand\">\n";
foreach ($list as $code => $name)
echo "<option value=\"$code\">$name</option>\n";
echo "</optgroup>\n";
}

关于php - 如何对相同的数组值进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5086541/

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