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

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化