笨鳥學php(六) 數組

來源:互聯網
上載者:User

標籤:style   使用   strong   資料   for   ar   line   size   

一、數組概述

1.1 數組是複合類型

1.2 數組中可以儲存任意長度的資料, 也可以儲存任意類型的資料


二、數組的類型

2.1 索引數組: 下標是順序整數作為索引

<?php$user[0] = 1;$user[1] = "zhangsan";$user[2] = "[email protected]";echo '<pre>';print_r($user);echo '</pre>';?>

2.2 關聯陣列: 下標是字串作為索引

<?php$user["id"] = 1;$user["name"] = "zhangsan";$user["email"] = "[email protected]";echo '<pre>';print_r($user);echo '</pre>';$user["name"] = "lisi";echo $user["name"];?>

三、數組的多種聲明方式

3.1 直接為數組元素賦值

      a. 如果索引下標不給值,就會從0開始順序索引
      b. 如果給出索引下標,下一個就會是從最大的開始增1

      c. 如果後面出現前面的下標,如果是賦值就是為前面的元素重新賦值
      d. 混合聲明時,索引和關聯不互相影響(不影響索引下標的聲明)


3.2 使用array()函數

      a.  預設是索引數組

      b. 如果為關聯陣列和索引數組指定下標,使用 鍵=>值
      c. 多個成員之前使用“,”分割

<?php$user1 = array (1, "zhsangsan", 10, "nan", "[email protected]");echo '<pre>';print_r($user1);echo '</pre>';/** Array(    [0] => 1    [1] => zhsangsan    [2] => 10    [3] => nan    [4] => [email protected] ) */$user2 = array("id"=>1, "name"=>"zhsangsan", "age"=>10, 100=>"nan", "[email protected]");echo '<pre>';print_r($user2);echo '</pre>';/** Array(    [id] => 1    [name] => zhsangsan    [age] => 10    [100] => nan    [101] => [email protected] ) */?>

重要知識點: 二維數組

<?php$info=array("user"=>array(array(1, "zansan", 10, "nan"),array(2, "lisi", 20, "nv") ));echo $info["user"][1][1]; // lisiecho '<pre>';print_r($info);echo '</pre>';/** Array (    [user] => Array        (            [0] => Array                (                    [0] => 1                    [1] => zansan                    [2] => 10                    [3] => nan                )            [1] => Array                (                    [0] => 2                    [1] => lisi                    [2] => 20                    [3] => nv                )        )) */?>

四、數組的遍曆

4.1 使用for語句迴圈遍曆(不推薦)

      局限性: 數組必須是索引數組, 而且下標必須是連續的 (然而索引數組下標可以不連續, 數組還可能是關聯陣列)


4.2 使用foreach語句迴圈遍曆(強烈推薦)

      迴圈次數由數組的元素個數決定, 每一次迴圈都會將數組中的元素分別賦值給後面的變數


4.3 使用while(), list(), each() 組合迴圈遍曆(不推薦)

      each() 函數:

      * 需要一個數組作為參數

      * 返回來的也是一個數組

      * 返回來的數組時0, 1, key, value四個下標, 0和key下標是當前數組元素的鍵, 1和value下標是當前數組元素的值

      * 預設當前元素就是第一個元素

      * 每執行一次後就會將當前元素向後移動

      * 如果已經到了最後還執行這個函數, 則返回false


      list() 函數:

      * list()=array(); 需要將一個數組賦值給這個函數

      * 數組中的元素個數要和list()函數中的參數個數相同
      * 數組中的每個元素值會賦值給list()函數中的每個參數,list()將每個參數轉為變數






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.