PHP编程指南我爱编程

PHP编程指南(六)数组

2018-04-17  本文已影响24人  爱吃馒头的二饼
数组的类型

索引数组

定义

$animal = array("monkey","dog","cat");
$animal[0] = "monkey";
$animal[1] = "dog";
$animal[2] = "cat";

获取指定索引位置上的值:

echo "$animal[0],$animal[1],$animal[2]";

遍历索引数组

<?php
    $animal[0] = "monkey";
    $animal[1] = "dog";
    $animal[2] = "cat";

    foreach ($animal as $a) {
        echo $a . "</br>";
    }
?>

索引数组的长度

通过count()函数可以计算数组的长度

echo count($animal);

关联数组

定义

$money = array("pen" => 20,"notes" => 5);
$money["pen"] = 20;
$money["notes"] = 5;

获取

echo $money["pen"];

遍历关联数组

<?php
    $money["pen"] = 20;
    $money["notes"] = 5;
    
    foreach($money as $key => $value) {
        echo "{$key}对应{$value}</br>";
    }
?>

多维数组

定义

如下是定义一个三行三列的多维数组:

    $multi = array
        (
            array(1,"pen",20),
            array(2,"notes",5),
            array(3,"eraser",2)
        );

遍历

需要使用for循环嵌套来实现多维数组的遍历

<?php
    $multi = array
        (
            array(1,"pen",20),
            array(2,"notes",5),
            array(3,"eraser",2)
        );

    for($row = 0;$row < 3; $row++) {
        for($col = 0;$col < 3;$col++) {
            echo "{$multi[$row][$col]} ";
        }
        echo "</br>";
    }
?>
多维数组遍历结果
上一篇下一篇

猜你喜欢

热点阅读