Php 尝试理解:从数据库中获取结果,并根据首选项键入每一行
上面的代码片段取自xenforo系统 问题: 尽管对该函数有评论,但仍然不了解“key”参数是如何工作的? 评论中说:Php 尝试理解:从数据库中获取结果,并根据首选项键入每一行,php,mysql,Php,Mysql,上面的代码片段取自xenforo系统 问题: 尽管对该函数有评论,但仍然不了解“key”参数是如何工作的? 评论中说: /** * 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
/**
* 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;
}
那么结果会是什么呢?生成的数组是一个关联数组,索引是其相应的
项id
因此,结果将是
* 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
...
基本上,key()返回当前数组位置的索引元素。更深入的是key()函数只返回内部指针当前指向的数组元素的键。它不会以任何方式移动指针。如果内部指针指向元素列表的末尾之外或数组为空,key()将返回NULL
关于这里的更多细节所以如果我想访问项目:title:car,我应该执行[2]['title'],对吗?
[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'),
......