php读取数组的三种方法
php读取数组主要有以下三种方法:
1,用for
1.<?php
2.$one = array(1, 2, 3, 4);
3.$two = array(array("tank",12412433),
4. array("ying",252523523),
5. array("zhang",656452345));
6.
7.for($i=0;$i<count($one);$i++){
8. echo $one[$i]."<br>";
9.}
10.
11.for($i=0;$i<count($two);$i++){
12. for($j=0;$j<count($two[$i]);$j++){
13. echo $two[$i][$j]."<br>";
14. }
15.}
16.
17.?>
<?php
$one = array(1, 2, 3, 4);
$two = array(array("tank",12412433),
array("ying",252523523),
array("zhang",656452345));
for($i=0;$i<count($one);$i++){
echo $one[$i]."<br>";
}
for($i=0;$i<count($two);$i++){
for($j=0;$j<count($two[$i]);$j++){
echo $two[$i][$j]."<br>";
}
}
?>刚接触php的时候,特别喜欢用,因为在学校的时候,学过C,根C里面的for循环差不多。不过for循环有一点不好,无法读取数组的下标。下标又是非常的重要。所以现在for用的很少了。
2,用foreach
1.$one = array(1, 2, 3, 4);
2.
3.$two = array("test1" =>array('name'=>"tank","phone"=>12412433),
4. "test2" => array('name'=>"ying","phone"=>252523523),
5. "test3" => array('name'=>"zhang","phone"=>656452345),);
6.
7.foreach ($one as $k=>$v) {
8. echo "key=".$k."&value=".$v."<br>";
9.}
10.
11.foreach ($two as $k=>$v) {
12. echo "key=$k<br>";
13. foreach($v as $value){
14. echo $value."<br>";
15. }
16.}
$one = array(1, 2, 3, 4);
$two = array("test1" =>array('name'=>"tank","phone"=>12412433),
"test2" => array('name'=>"ying","phone"=>252523523),
"test3" => array('name'=>"zhang","phone"=>656452345),);
foreach ($one as $k=>$v) {
echo "key=".$k."&value=".$v."<br>";
}
foreach ($two as $k=>$v) {
echo "key=$k<br>";
foreach($v as $value){
echo $value."<br>";
}
}用foreach呢,就解决了不能读取下标的问题了。在应用中就更为广泛了。
3,用list each
1.$one = array(1, 2, 3, 4);
2.
3.$two = array("test1" =>array('name'=>"tank","phone"=>12412433),
4. "test2" => array('name'=>"ying","phone"=>252523523),
5. "test3" => array('name'=>"zhang","phone"=>656452345),);
6.
7.list($f, $s,$t) = $one;
8.echo $f.$s.$t;
9.
10.while (list($k, $v) = each($one)) {
11. echo "key=$k&v=$v<br>";
12.}
13.
14.while (list($k, $v) = each($two)) {
15. while (list($key, $value) = each($v)) {
16. echo $value."<br>";
17. }
18.}
$one = array(1, 2, 3, 4);
$two = array("test1" =>array('name'=>"tank","phone"=>12412433),
"test2" => array('name'=>"ying","phone"=>252523523),
"test3" => array('name'=>"zhang","phone"=>656452345),);
list($f, $s,$t) = $one;
echo $f.$s.$t;
while (list($k, $v) = each($one)) {
echo "key=$k&v=$v<br>";
}
while (list($k, $v) = each($two)) {
while (list($key, $value) = each($v)) {
echo $value."<br>";
}
}list each结合使用的时候,其实根foreach差不多,只不过用list each,还是不习惯,感觉不是很爽。这三种方法,foreach是最佳选择。