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 系统。

问题:

虽然对这个函数有评论,但还是不明白 'key' 参数是如何工作的?在评论中,它说:

 * 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
...

那么结果会是什么?

4

2 回答 2

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'),
......
于 2013-06-22T02:34:12.907 回答
0

基本上,key() 返回当前数组位置的索引元素。更深入的是key()函数只是返回当前由内部指针指向的数组元素的键。它不会以任何方式移动指针。如果内部指针指向元素列表末尾之外或数组为空,则 key() 返回 NULL。

更多细节在这里http://php.net/manual/en/function.key.php

于 2013-06-22T02:41:15.460 回答