我有以下PHP代码:
<?php
$states = array("Alabama","Alaska","Arizona","Arkansas",
"California","Colorado","Connecticut","Delaware",
"Florida","Georgia","Hawaii","Idaho",
"Illinois","Indiana","Iowa","Kansas","Kentucky");
$stateAbbr = array("AL","AK","AZ","AR","CA","CO","CT","DE",
"FL","GA","HI","ID","IL","IN","IA","KS","KY");
?>
<!DOCTYPE html>
<html>
<body>
<h1>List of States</h1>
</body>
</html>
现在我需要添加一个PHP代码,通过循环遍历所有元素,使用for循环将状态和状态缩写打印为表格,并在每个索引
可以对li
使用double foreach<?php
foreach( $states as $index => $state ) {
echo "<li>" . $state . ' - ' . $stateAbbr[$index] ."</li>
}
echo "</ul>"
?>
您还可以组合数组,然后循环抛出,创建表行。
<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>
你可以这样创建你的数组:
<?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>
问候。