PHP使用for循环和echo元素

时间:2016-07-02 18:13:22

标签: php loops echo element

我有以下PHP代码:

word = "Stackoverflow is awesome!"
word.scan(/(.)(.)?/).inject('') {|s,(x,y)| s << x.upcase << y.to_s.downcase}

现在我需要添加一个PHP代码,通过循环遍历所有元素,使用for循环和每个索引处两个数组的echo元素,将状态和状态缩写作为表打印

3 个答案:

答案 0 :(得分:2)

你可以在li

上使用双重foreach
<?php 

     foreach( $states as $index => $state ) {
          echo "<li>" . $state . ' - ' . $stateAbbr[$index] ."</li>
    }
    echo "</ul>"
?>

答案 1 :(得分:0)

您也可以组合数组然后循环抛出,创建表行。

    <table>
      <thead>
        <tr>
          <th>Code</th>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>
      <?php
        foreach (array_combine($stateAbbr, $states) as $code => $name) {
            echo '<tr><td>' . $code . '</td><td>' . $name . '</td></tr>';
        }
      ?>
      </tbody>
    </table>

答案 2 :(得分:0)

你可以像这样制作你的数组:

<?php
$states = array(
"Alabama" => "AL",
"Alaska" => "AK",
"Arizona" => "AZ",
"Arkansas" => "AR", 
"California" => "CA",
"Colorado" => "CO",
"Connecticut" => "CT",
"Delaware" => "DE", 
"Florida" => "FL",
"Georgia" => "GA",
"Hawaii" => "HI",
"Idaho" => "ID", 
"Illinois" => "IL",
"Indiana" => "IN",
"Iowa" => "IA",
"Kansas" => "KS",
"Kentucky" => "KY"
);

然后像这样或任何你想要的标签打印:

<!DOCTYPE html>
<html>
<body>
    <h1>List of States</h1>
    <?php
        foreach($states as $state => $abbr)
        {
            echo $state.' - '.$abbr.'<br />';
        } 
    ?>
</body>
</html>

问候。