php list函數用法

來源:互聯網
上載者:User

注: list() 僅能用於數字索引的數組並假定數字索引從 0 開始。

例子 1. list() 例子

 代碼如下 複製代碼
<?php
 
$info = array('coffee', 'brown', 'caffeine');
 
// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.n";
 
// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.n";
 
// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!n";
 
?>

例子 2. 使用 list() 的例子

 代碼如下 複製代碼
<table>
<tr>
  <th>Employee name</th>
  <th>Salary</th>
</tr>
 
<?php
 
$result = mysql_query("SELECT id, name, salary FROM employees",$conn);
while (list($id, $name, $salary) = mysql_fetch_row($result)) {
    echo " <tr>n".
         "  <td><a href="info.php?id=$id">$name</a></td>n".
         "  <td>$salary</td>n".
         " </tr>n";
}
 
?>
 
</table>

警告
list() 從最右邊一個參數開始賦值。如果你用單純的變數,不用擔心這一點。但是如果你用了具有索引的數組,通常你期望得到的結果和在 list() 中寫的一樣是從左至右的,但實際上不是。是以相反順序賦值的。

例子 3. 在 list() 中使用數組索引

 代碼如下 複製代碼
<?php
$info = array('coffee', 'brown', 'caffeine');
list($a[0], $a[1], $a[2]) = $info;
var_dump($a);
?>

產生如下輸出(注意單元順序和 list() 文法中所寫的順序的比較):

 代碼如下 複製代碼

array(3) {
  [2]=>
  string(8) "caffeine"
  [1]=>
  string(5) "brown"
  [0]=>
  string(6) "coffee"
}

聯繫我們

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