dongzouhe9734 2013-06-07 13:41
浏览 38
已采纳

PHP从分隔字符串创建选项列表而不重复值

I have a string with values (which are suburbs) like so:

$suburbs = "Mawson, Elizabeth, Burnside, Elizbeth, Mawson";

There COULD be double ups in the suburbs that the string contains. I can't change this fact.

What I am trying to do is create an option list for a drop down menu that a user will use. I do not want to display the same suburb twice( or more for that matter).

What I have so far:

$suburbs = "Mawson, Elizabeth, Burnside, Elizbeth, Mawson";
//Explode the suburbs string delimited by a comma
$boom = explode(',', $suburbs);

foreach($boom as $b)
{
$suburbOptionList .= '<option value='.$b.'>'.$b.'</option>';
}
?>
<select> <?php
echo $suburbOptionList;
?>
</select>

I know that this will simply display all of the options but I really don't know how to display each suburb only once. Ive tried a few foreach,and if combinations but they look ugly and work just as bad.

Any help would be appreciated. Cheers in advance!

  • 写回答

1条回答 默认 最新

  • dow5001 2013-06-07 13:44
    关注

    Pass $boom through array_unique() and you'll be fine.

    $bada_boom = array_unique($boom);
    

    P.S.: This will not help if you have typos or variations in duplicates. (Elizbeth != Elizabeth). In that case you will need to get creative.

    Also, hw (in comments) made a good point about trimming whitespaces. If the suburbs come from an untrusted source and are improperly formatted, you may need to normalize them. This means trimming whitespaces and normalizing capitals:

    $boom = array_walk($boom, 'trim');
    $boom = array_walk($boom, 'strtolower');
    $bada_boom = array_unique($boom);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于哈夫曼树应用得到一些问题
  • ¥15 使用sql server语句实现下面两个实验(需要代码和运行结果截图)
  • ¥20 用web解决,要给我一个完整的网页,符合上述的要求
  • ¥20 求个sql server代码和结果的图 两道题
  • ¥15 银河麒麟操作系统无法使用U盘
  • ¥100 寻找:光电二极管电路设计服务
  • ¥15 YOLOv5改进后的结构图
  • ¥15 全志v3s怎么设置高速时钟,使用的荔枝派zero开发板,串口2需要921600的波特率
  • ¥15 关于#单片机#的问题:Lora通讯模块hc-14电路图求内部原理图
  • ¥50 esp32 wroom 32e 芯片解锁