while
只要指定的条件成立,则循环执行代码块
do…while
首先执行一次代码块,然后在指定的条件成立时重复这个循环
for
循环执行代码块指定的次数
foreach
根据数组中每个元素来循环代码块
先我们利用php自带函数对php数组进行遍历
随手可得array_keys()和array_values()函数以用来得到数组中所有关键字和对应的值的列表.
利用foreach 遍历php数组
PHP foreach() 语法结构用于遍历操作或输出数组,foreach()
仅能用于遍历数组或对象,当试图将其用于其它数据类型或者一个未初始化的变量时会产生错误.
$list = array(
'upid'=>'10086',
'title'=>'会社新聞',
'titleList'=>array(
'id'=>'9999',
'title'=>'新聞テートルリスト',
'intime'=>'2016-10-24'
)
);
//'upid'=>'10086'
echo $list['upid'],"";
//'title'=>'会社新聞'
echo $list['title'],"";
//titleList遍历
foreach ($list['titleList'] as $key => $value) {
echo $key,"---->",$value,"";
}
//titleList遍历
echo "--------------------------------
";
foreach ($list['titleList'] as $key => $value) {
echo $list['titleList'][$key],"";
}
echo "--------------------------------
";
foreach ($list['titleList'] as $allList) {
echo $allList,"";
}
?>
$people_age = array("wang"=>"18", "li"=>"20", "zhang"=>"25");
foreach ($people_age as $name=>$age) {
echo $name,'=>',$age,'';
}
?>
$database_list=array("oracle","mysql","db2","informix","mysql","postgre_sql");
foreach ($database_list as $key => $value) {
echo $database_list[$key],"";
}
foreach ($database_list as $key => $value) {
echo $value,"";
}
?>
for() 循环遍历数组
如果是操作连续键值的数组,也可以采用 for() 循环来遍历数组:
$database_list=array("oracle","mysql","db2","informix","mysql","postgre_sql");
$count=count($database_list);
for ($i=0; $i < $count; $i++) {
echo $database_list[$i],"";
}
?>
list函数
list() 函数用数组中的元素为一组变量赋值.
注意,与 array() 类似,list() 实际上是一种语言结构,不是函数.
语法
list(var1,var2…)参数 描述
var1 必需.第一个需要赋值的变量.
var2 可选.可以有多个变量.
提示和注释
注释:该函数只用于数字索引的数组,且假定数字索引从 0 开始
*/
$database_list=array("oracle","mysql","db2","informix","mysql","postgre_sql");
while(list($key,$val) = each($database_list)) {
echo $val,"
";
}
while ($i <= count($database_list)) {
echo $database_list[$i],"
";
$i++;
}
?>