• php数组


    php中数组分为:索引数组和关联数组;

      索引数组:数组的索引值是整数,以0开始,通过位置来标识的时候使用索引数,下标从0开始;

      关联数组:以字符串作为索引,关联数组更像操作表,索引值为列名,用于访问列的数据

      key-value

    数组的定义:(两种)

    <?php
        //数组的定义
        /*
        $arr1[0] = "PHP";
        $arr1[1] = "MySQL";
        $arr1[2] = "Apache";
        $arr1[3] = "Linux";
       
        $arr1[] = "PHP";
        $arr1[] = "MySQL";
        $arr1[] = "Apache";
        $arr1[] = "Linux";
        */
        
        //关联数组的直接定义
        $arr1["brand"] = "iphone5";
        $arr1["os"] = "ios";
        $arr1["price"] = 4980;
        //打印数组,print_r
        print_r($arr1);
    
    ?>
    <?php
        //使用array语句来定义数组
        $arr1 = array("PHP","MySQL","Apache","Linux");
        
        $arr2 = array(
            "brand" => "Lumia 900",
            "os" => "wp8",
            "price" => 4700
        );
        echo "<pre>";
        print_r($arr2);
        echo "</pre>";    
    ?>

    数组的遍历:

    数组的遍历分为三种,for、foreach、while+list+each

    for有局限性,只能遍历关联数组;

    <?php
        // 数组的遍历
        $arr1 = array(2,3,4,5,6,7);
        $arr2 =  array(
            "brand" => "Lumia 900",
            "os" => "wp8",
            "price" => 4700
        );
        //不推荐$i < count($arr1)
        $len = count($arr2);
    
        for($i = 0; $i < $len; $i++){
            echo $arr2[$i]."<br />";
        }
    ?>

    foreach几乎专门为数组量身定制

    1、foreach($arr as $val)

    {echo $val.'<br/>';}

    2、foreach($arr as $key =>$value)

    {echo $key.='='.$value.'<br/>';}

    <?php
       
    //foreach 的用法
        $arr2array(
           
    "brand" => "Lumia 900",
            "os" => "wp8",
            "price" => 4700
        );
       
       
    $arr1 = array("PHP","MySQL","Apache","Linux");
       
       
    foreach($arr1 as $key => $val){
           
    echo $key."=".$val."<br />";
        }
    ?>

    <?php
        //while+ list + each
        $arr1 = array(
            "brand" => "Lumia 900",
            "os" => "wp8",
            "price" => 4700
        );
        echo "<pre>";
        print_r(each($arr1));
        echo "</pre>";
    
        list($k,$v) = each($arr1);
        echo $k."<br />";
        echo $v."<br />";
        /*
        while(list($k,$v) = each($arr1)){
            echo $k ."=".$v."<br />";
        */
        }    
    ?>

    while+list+each:使用起来比较麻烦,不建议;list是种结构,只针对索引有效,仅能用于数字索引的数组并假定数字索引从0开始

    除非数组是被引用,foreach所操作的是指定数组的一个拷贝,而不是该数组本身,在php里数组是通过值传递,对象是引用传值;

  • 相关阅读:
    OO第二单元——多线程(电梯)
    OO前三次作业思考(第一次OO——Blog)
    P2016 战略游戏——树形DP大水题
    P1108 低价购买——最长下降子序列+方案数
    P1041 传染病控制——暴力遍历所有相同深度的节点
    P2502 [HAOI2006]旅行——暴力和并查集的完美结合
    2019.10.25字符串——zr
    P3719 [AHOI2017初中组]rexp——递归模拟
    树状数组优化最长上升子序列
    P1378 油滴扩展——搜索小记
  • 原文地址:https://www.cnblogs.com/RightDear/p/2754445.html
Copyright © 2020-2023  润新知