Home >Backend Development >PHP Tutorial >How to traverse a two-dimensional array with different forms of output in PHP

How to traverse a two-dimensional array with different forms of output in PHP

一个新手
一个新手Original
2017-09-12 10:57:231869browse

<body>
<?php //定义二维索引数组
$arr = array(    
    array("101","李军","男","1976-02-20","95033"),    
    array("103","陆君","男","1974-06-03","95031"),    
    array("105","匡明","男","1975-10-02","95031"),    
    array("107","王丽","女","1976-01-23","95033"),    
    array("108","曾华","男","1977-08-01","95033"),    
    array("109","王芳","女","1975-02-10","95031"));

The first output form (echo statement)

/* echo "<table width=100% border=&#39;1&#39;>";
echo "<tr><td>Sno</td><td>Sname</td><td>Ssex</td><td>Sbirthday</td><td>Class</td></tr>";
foreach($arr as $v){
    echo "<tr><td>{$v[0]}</td><td>{$v[1]}</td><td>{$v[2]}</td><td>{$v[3]}</td><td>{$v[4]}</td></tr>";
}
echo "</table>" ;
</body>

The second output form (HTML code table Output)

<body>
<table width=100% border=&#39;1&#39;>
    <tr>
        <td>Sno</td>
        <td>Sname</td>
        <td>Ssex</td>
        <td>Sbirthday</td>
        <td>Class</td>
    </tr>

<?php 
foreach($arr as $v){
        echo "<tr>
        <td>{$v[0]}</td>
        <td>{$v[1]}</td>
        <td>{$v[2]}</td>
        <td>{$v[3]}</td>
        <td>{$v[4]}</td>
        <tr>";
};
?>
</table>
</body>

The third output form (drop-down list)

<body>
<?php
$arr = array(
    array("1","山东"),
    array("2","北京"),
    array("3","上海"),
    array("4","广州"),
    array("5","香港"),
    array("6","澳门")
); 
?>

<select id="nation">
<option value="all">请选择</option>

<?php 
foreach($arr as $v){
    echo "<option value=&#39;$v[0]&#39;>$v[1]</option>";
};
?>
</select>
</body>

The fourth output form

<body>
取数组中输出的总数
$arr = array(
    array(4)
);
echo $arr[0][0];

取数组中一组数据
$arr = array(
    array("1","上海")
);
echo "<option value=&#39;{$arr[0][0]}&#39;>{$arr[0][1]}</option>";
取数组中任意一个数据
$arr = array(
    array("1","台湾"),
    array("2","北京"),
    array("3","上海"),
    array("4","广州"),
    array("5","香港")
);
echo "<option value=&#39;{$arr[4][0]}&#39;>{$arr[4][1]}</option>";
?>
</body>

The above is the detailed content of How to traverse a two-dimensional array with different forms of output in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn