How do I group same array value

后端 未结 1 665
情话喂你
情话喂你 2020-12-28 11:04

Example my array

$options = array(
    array(\"brand\" => \"Puma\",\"code\" => \"p01\",\"name\" => \"Puma One\"),
    array(\"brand\" => \"Puma\"         


        
相关标签:
1条回答
  • 2020-12-28 11:26

    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";
    }
    
    0 讨论(0)
提交回复
热议问题