gpt4 book ai didi

php - 试图理解:Fetches results from the database with each row keyed according to preference

转载 作者:行者123 更新时间:2023-11-30 01:32:53 25 4
gpt4 key购买 nike

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

那么结果会是什么呢?

最佳答案

生成的数组是一个关联数组,其索引为其对应的 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'),
......

关于php - 试图理解:Fetches results from the database with each row keyed according to preference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17246766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com