php 如何将相同的数组值分组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5086541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:45:44  来源:igfitidea点击:

How do I group same array value

phpmultidimensional-array

提问by Unknown Error

Example my array

以我的数组为例

$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")
);

How to generate this array to be

如何生成这个数组

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

Or you can suggestion better array according to my select option output. Let me know.

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

回答by casablanca

You can create another array keyed by the brand:

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

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

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

This will produce an array like this:

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

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

If you can directly format your array like this, you can skip the first step.

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

Then iterate over this new array and output the options:

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

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";
}