标签:
PHP中的for循环
<?php
$arr = array("a", "b", "c");
for( $i = 0; $i < count($arr); $i++){
echo $arr[$i];
};
// count 相当于js中的 length
?>
优化一下
<?php
$arr = array("a", "b", "c", ‘d‘);
$num = count($arr);
for( $i = 0; $i < $num; $i++){
echo $arr[$i].‘<br>‘;
};
// count 相当于js中的 length
?>
在php中, for循环其实并不常用, 最常用的还是foreach循环
foreach循环
<?php $arr = array("a", "b", "c", ‘d‘, ‘e‘); foreach($arr as $value){ echo "{$value}<br>"; }; ?>
foreach的强大之处在于可以输出下标
<?php $arr = array("a", "b", "c", ‘d‘, ‘one‘=>‘e‘); foreach($arr as $key => $value){ echo "{$key}---{$value}<br>"; }; ?>
看一个数组转成表格的实例
<?php $group = [ [‘name‘ => ‘zs‘ , ‘age‘ => 20 , ‘sex‘ => ‘男‘ , ‘email‘ => ‘aaa@163.com‘], [‘name‘ => ‘as‘ , ‘age‘ => 17 , ‘sex‘ => ‘女‘ , ‘email‘ => ‘aaa@163.com‘], [‘name‘ => ‘zs‘ , ‘age‘ => 20 , ‘sex‘ => ‘男‘ , ‘email‘ => ‘aaa@163.com‘], [‘name‘ => ‘as‘ , ‘age‘ => 20 , ‘sex‘ => ‘女‘ , ‘email‘ => ‘aaa@163.com‘], [‘name‘ => ‘zs‘ , ‘age‘ => 20 , ‘sex‘ => ‘男‘ , ‘email‘ => ‘aaa@163.com‘], [‘name‘ => ‘as‘ , ‘age‘ => 20 , ‘sex‘ => ‘女‘ , ‘email‘ => ‘aaa@163.com‘], [‘name‘ => ‘zs‘ , ‘age‘ => 20 , ‘sex‘ => ‘男‘ , ‘email‘ => ‘aaa@163.com‘], [‘name‘ => ‘as‘ , ‘age‘ => 20 , ‘sex‘ => ‘女‘ , ‘email‘ => ‘aaa@163.com‘] ]; echo ‘<table border="1" width="800" align="center">‘; echo ‘<caption><h1>数组转表格实例</h1></caption>‘; // foreach循环 foreach($group as $row){ echo ‘<tr>‘; foreach($row as $col){ echo ‘<td>‘.$col.‘</td>‘; }; echo ‘</tr>‘; }; ?>
标签:
原文地址:http://www.cnblogs.com/carol1987/p/5454309.html