《PHP實戰(zhàn):PHP獲取數(shù)組的鍵與值方法小結》要點:
本文介紹了PHP實戰(zhàn):PHP獲取數(shù)組的鍵與值方法小結,希望對您有用。如果有疑問,可以聯(lián)系我們。
PHP實例本文實例講述了PHP獲取數(shù)組的鍵與值辦法.分享給大家供大家參考.具體如下:
PHP實例使用數(shù)組的過程中經(jīng)常要遍歷數(shù)組.通常需要遍歷數(shù)組并獲得各個鍵或值(或者同時獲得鍵和值),所以毫不奇怪,PHP為此提供了一些函數(shù)來滿足需求.許多函數(shù)能完成兩項任務,不僅能獲取當前指針位置的鍵或值,還能將指針移向下一個適當?shù)奈恢?
PHP實例獲取當前數(shù)組鍵 key()
PHP實例key()函數(shù)返回input_array中當前指針所在位置的鍵.其形式如下:
PHP實例mixed key(array array)
PHP實例下面的例子通過迭代處理數(shù)組并移動指針來輸出$fruits數(shù)組的鍵:
PHP實例
$fruits = array("apple"=>"red", "banana"=>"yellow");
while ($key = key($fruits)) {
printf("%s <br />", $key);
next($fruits);
}
// apple
// banana
PHP實例注意,每次調用key()時不會移動指針.為此需要使用next()函數(shù),這個函數(shù)的唯一作用就是完成推進指針的任務.
PHP實例獲取當前數(shù)組值 current()
PHP實例current()函數(shù)返回數(shù)組中當前指針所在位置的數(shù)組值.其形式如下:
PHP實例mixed current(array array)
PHP實例下面修改前面的例子,這一次我們要獲取數(shù)組值:
PHP實例
$fruits = array("apple"=>"red", "banana"=>"yellow");
while ($fruit = current($fruits)) {
printf("%s <br />", $fruit);
next($fruits);
}
// red
// yellow
PHP實例獲取當前數(shù)組鍵和值 each()
PHP實例each()函數(shù)返回input_array的當前鍵/值對,并將指針推進一個位置.其形式如下:
PHP實例array each(array array)
PHP實例返回的數(shù)組包含四個鍵,鍵0和key包含鍵名,而鍵1和value包含相應的數(shù)據(jù).如果執(zhí)行each()前指針位于數(shù)組末尾,則返回false.
PHP實例
$fruits = array("apple", "banana", "orange", "pear");
print_r ( each($fruits) );
// Array ( [1] => apple [value] => apple [0] => 0 [key] => 0 )
PHP實例each() 經(jīng)常和 list() 結合使用來遍歷數(shù)組.本例與上例類似,不過循環(huán)輸出了整個數(shù)組:
PHP實例
$fruits = array("apple", "banana", "orange", "pear");
reset($fruits);
while (list($key, $val) = each($fruits))
{
echo "$key => $val<br />";
}
// 0 => apple
// 1 => banana
// 2 => orange
// 3 => pear
PHP實例因為將一個數(shù)組賦值給另一個數(shù)組時會重置原來的數(shù)組指針,因此在上例中如果我們在循環(huán)內(nèi)部將 $fruits 賦給了另一個變量的話將會導致無限循環(huán).
PHP實例這就完成了數(shù)組的遍歷.
PHP實例希望本文所述對大家的jQuery程序設計有所贊助.
歡迎參與《PHP實戰(zhàn):PHP獲取數(shù)組的鍵與值方法小結》討論,分享您的想法,維易PHP學院為您提供專業(yè)教程。
轉載請注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/10349.html