根据自定义字段选择组


Optgroup by custom field

我目前正在使用Wordpress创建和填充<select><option> s。

<?php if( $lh_loop->have_posts() ): ?>
  <select class="mousechoice left">
    <?php while( $lh_loop->have_posts() ) : $lh_loop->the_post();?>
      <optgroup label="<?php echo get_field("company_name") ?>">
        <option data-id="<?php echo $post->post_name; ?>"><?php the_title(); ?></option>
      </optgroup>
    <?php endwhile; ?>
  </select>
<?php endif; ?>

显示如下:

<select class="mousechoice left">
  <optgroup label="SteelSeries">
    <option data-id="sensei">Sensei</option>
  </optgroup>
  <optgroup label="Razer">
    <option data-id="deathadder">Deathadder</option>
  </optgroup>
  <optgroup label="SteelSeries">
    <option data-id="kana">Kana</option>
  </optgroup>
</select>

我想将具有相同公司名称的帖子分组到<optgroup>的方式。结果是:

<select class="mousechoice left">
  <optgroup label="SteelSeries">
    <option data-id="sensei">Sensei</option>
    <option data-id="kana">Kana</option>
  </optgroup>
  <optgroup label="Razer">
    <option data-id="deathadder">Deathadder</option>
  </optgroup>
</select>

我尝试将当前帖子的公司与前一个帖子的公司进行比较,但意识到具有相同公司名称的帖子可能在另一个具有不同公司名称的帖子之后或之前。

我知道我也可以使用if语句来指定每个公司名称,但我想要一个解决方案,允许其他公司名称尚未输入到Wordpress。

如果您想按某些值对数组中的所有元素进行分组,我喜欢先遍历数组以对其进行排序,然后在单独的循环中进行显示。

所以我会把每个元素放入一个数组中,这个数组中有我想要分组的值作为键。

所以我想创建一个像

这样的数组
 ['company A' =>[ [1 => 'option 1'],
                  [2 => 'option 2'],
                  ...
                ],
  'company B' =>[ [1 => 'option 3'],
                  [2 => 'option 4'],
                  ...
                 ],
   ...
  ]

要创建这个数组,您可以使用(未测试)

$grouped = array();
while( $lh_loop->have_posts() ) : 
     $lh_loop->the_post();
     $key = get_field("company_name") 
     $subkey = $post->post_name; 
     $display = the_title();   
     if (empty($grouped[$key]){ //if they key isn't set yet
         //add the key to the array as a new element
         $grouped[] = array($key=>array($subkey=>$title));  
     }else{
         //else add to existing key
         $grouped[$key][] = array($subkey=>$title); 
     }         
endwhile;

然后,要显示列表,执行如下命令

foreach ($grouped as $comp => $group){
    echo "<optgroup label='"$comp'">";
     foreach ($group as $key => $val){
          echo "<option data-id='"$key'">$val</option>";
     }
     echo "</optgroup>";
}