2013-06-22 13 views
0
/** 
    * Fetches results from the database with each row keyed according to preference. 
    * The 'key' parameter provides the column name with which to key the result. 
    * For example, calling fetchAllKeyed('SELECT item_id, title, date FROM table', 'item_id') 
    * would result in an array keyed by item_id: 
    * [$itemId] => array('item_id' => $itemId, 'title' => $title, 'date' => $date) 
    * 
    * Note that the specified key must exist in the query result, or it will be ignored. 
    * 
    * @param string SQL to execute 
    * @param string Column with which to key the results array 
    * @param mixed Parameters for the SQL 
    * 
    * @return array 
    */ 
    public function fetchAllKeyed($sql, $key, $bind = array()) 
    { 
     $results = array(); 
     $i = 0; 

     $stmt = $this->_getDb()->query($sql, $bind, Zend_Db::FETCH_ASSOC); 
     while ($row = $stmt->fetch()) 
     { 
      $i++; 
      $results[(isset($row[$key]) ? $row[$key] : $i)] = $row; 
     } 

     return $results; 
    } 

以上代碼片段取自xenforo系統。試圖理解:從數據庫獲取結果,根據首選項鍵入每行

問:

雖然有此功能的意見,仍然不知道如何做「關鍵」參數的工作? 在評論,有人說:

* For example, calling fetchAllKeyed('SELECT item_id, title, date FROM table', 'item_id') 
* would result in an array keyed by item_id: 
* [$itemId] => array('item_id' => $itemId, 'title' => $title, 'date' => $date) 

so if the table looks like this: 
item_id title  date 
1   book  2000 
2   car  2000 
3   laptop 2001 
... 

所以會是什麼結果呢?

回答

0

生成的數組是一個索引與其對應的item_id的關聯數組。

所以結果將是

[1]=>array('item_id' => 1, 'title' => 'book', 'date' => '2000'), 
[2]=>array('item_id' => 2, 'title' => 'car', 'date' => '2000'), 
[3]=>array('item_id' => 3, 'title' => 'laptop', 'date' => '2001'), 
...... 
+0

更多細節,所以如果我要訪問的項目:標題:汽車,我應該做的[2] [「標題」],對不對? – user2507818

+0

@ user2507818是的。 :) –

0

基本上,鍵()返回當前陣列的位置的索引元素。更深入的是鍵()函數只是返回當前內部指針指向的數組元素的鍵。它不會以任何方式移動指針。如果內部指針指向元素列表末尾或數組爲空,則key()返回NULL。在這裏http://php.net/manual/en/function.key.php

相關問題