将数组内容排序为字母表组/列

时间:2015-09-24 13:28:04

标签: php arrays list

包含意大利所有城市的PHP数组(完成此操作)

生成以字母G,B和I开头的所有城市的列表。 (无法弄清楚如何做到这一点)我已经制作了专栏和标题。只需要将数据放入列中。

$cities = array("Rome", "Milan", "Turin", "Naples", "Venice-Padua", "Florence",

    "Bari", "Palermo", "Catania",

    "Brescia", "Genoa", "Messina-Reggio Calabria", "Rimini", "Bologna", "Modena",

    "Verona", "Pisa-livorno", "Pescara",

    "Versilia", "Vicenza", "Cagliari", "Taranto", "Trieste", "Ancona", "Perugia",

    "Lecce", "Reggio nell'Emilia" ) ;





    ?>

    <div class = "container">
        <div class = "row">
            <div class = "col-xs-12 col-md-5 col-md-push-2">

    <h1>Cties starting with G</h1>
        <p></p>


   </div>

这就是我到目前为止所做的。

2 个答案:

答案 0 :(得分:0)

试试这样:

foreach($cities as $data){
    if(substr($data,0, 1)=="G"){
        echo $data."</br>";
    }
}

foreach($cities as $data){
    if(substr($data,0, 1)=="B"){
        echo $data."</br>";
    }
}

答案 1 :(得分:0)

使用foreach循环和简单的检查:

<div class = "col-xs-12 col-md-5 col-md-push-2">
    <h1>Cities starting with B</h1>
    <?php
        foreach ($cities as $city):
          if ($city[0] == "B"):
    ?>
    <p><?= $city;?></p>
    <?php
          endif;
        endforeach;
    ?>
</div>

<div class = "col-xs-12 col-md-5 col-md-push-2">
    <h1>Cities starting with G</h1>
    <?php
        foreach ($cities as $city):
          if ($city[0] == "G"):
    ?>
    <p><?= $city;?></p>
    <?php
          endif;
        endforeach;
    ?>
</div>