PHP擷取數組的鍵與值方法小結_PHP教程

來源:互聯網
上載者:User

PHP擷取數組的鍵與值方法小結


使用數組的過程中經常要遍曆數組。通常需要遍曆數組並獲得各個鍵或值(或者同時獲得鍵和值),所以毫不奇怪,PHP為此提供了一些函數來滿足需求。許多函數能完成兩項任務,不僅能擷取當前指標位置的鍵或值,還能將指標移向下一個適當的位置。

擷取當前數組鍵 key()

key()函數返回input_array中當前指標所在位置的鍵。其形式如下:

mixed key(array array)

下面的例子通過迭代處理數組並移動指標來輸出$fruits數組的鍵:

1

2

3

4

5

6

7

$fruits = array("apple"=>"red", "banana"=>"yellow");

while ($key = key($fruits)) {

printf("%s
", $key);

next($fruits);

}

// apple

// banana

注意,每次調用key()時不會移動指標。為此需要使用next()函數,這個函數的唯一作用就是完成推進指標的任務。

擷取當前數組值 current()

current()函數返回數組中當前指標所在位置的數組值。其形式如下:

mixed current(array array)

下面修改前面的例子,這一次我們要擷取數組值:

1

2

3

4

5

6

7

$fruits = array("apple"=>"red", "banana"=>"yellow");

while ($fruit = current($fruits)) {

printf("%s
", $fruit);

next($fruits);

}

// red

// yellow

擷取當前數組鍵和值 each()

each()函數返回input_array的當前鍵/值對,並將指標推進一個位置。其形式如下:

array each(array array)

返回的數組包含四個鍵,鍵0和key包含鍵名,而鍵1和value包含相應的資料。如果執行each()前指標位於數組末尾,則返回false。

1

2

3

$fruits = array("apple", "banana", "orange", "pear");

print_r ( each($fruits) );

// Array ( [1] => apple [value] => apple [0] => 0 [key] => 0 )

each() 經常和 list() 結合使用來遍曆數組。本例與上例類似,不過迴圈輸出了整個數組:

1

2

3

4

5

6

7

8

9

10

$fruits = array("apple", "banana", "orange", "pear");

reset($fruits);

while (list($key, $val) = each($fruits))

{

echo "$key => $val
";

}

// 0 => apple

// 1 => banana

// 2 => orange

// 3 => pear

因為將一個數組賦值給另一個數組時會重設原來的數組指標,因此在上例中如果我們在迴圈內部將 $fruits 賦給了另一個變數的話將會導致無限迴圈。

這就完成了數組的遍曆。

http://www.bkjia.com/PHPjc/1015876.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1015876.htmlTechArticlePHP擷取數組的鍵與值方法小結 使用數組的過程中經常要遍曆數組。通常需要遍曆數組並獲得各個鍵或值(或者同時獲得鍵和值),所以毫不...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.