duanping2005 2015-08-10 03:50
浏览 30
已采纳

在显示视图中的分隔数据时,需要分隔带逗号的表列的值

I am being working on a project where i have a value in table with column "teams" and on that column i have one record with data like this "India, Nepal, Pakistan, Singapore".

In a view page i need to show the column "teams" with one value in a row. Like this:

<select name="tournament_team" class="form-control" >
    <option value=''>--- Select Team ---</option>
    <option value='india'>India</option>
    <option value='nepal'>Nepal</option>
    <option value='pakistan'>Pakistan</option>
    <option value='singapore'>Singapore</option>
</select>

How i can get separate value of one column by recognizing it by a comma ?

Thank in advance.

  • 写回答

2条回答 默认 最新

  • duanguoping2016 2015-08-10 04:08
    关注

    Typically you can use explode with this, however just using explode is a naive approach as there is a bit of cleanup to be done,

     $array =  array_filter( array_map('trim', explode(',', $teams ) ) );
    

    This does 3 things.

    • explode $teams by comma
    • array map, which runs a function against each item, in this case trim which removes whitespace
    • array filter which removes empty items just in case you have an item like this item,, - note though that array_filter will also remove elements with false and 0 as well as empty ones, but in this case it should be sufficient.

    Now converting the array to your markup should be relativity trivial,

    echo '<select name="tournament_team" class="form-control" >';
    echo '<option value="">--- Select Team ---</option>';
    foreach( $array as $item ){
        if($_POST['tournament_team'] == $item){
            $selected = ' selected="selected"';
        }else{
            $selected = '';
        }
          echo '<option value="'.$item.'"'.$selected.'>'.$item.'</option>';
    }
    echo '</select>';
    

    There is no need to select the default item, if it's rendered first and there is no selection then it will be selected by default, the $selection is just for form stickiness and you can omit or modify that as your needs dictate.

    Last thing is you'll have to watch the casing here, because you have mixed casing so I am not 100% sure which you want, for example india vs India.

    To lowercase use strtolower() to uppercase the first letter only use ucfirst()

    Also I haven't tested this but it should be fairly close minus any typos, that I might have made.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?