2

我最近构建了一个用于自动分页和排序查询结果的类,它适用于 PDO。

以下是我从 MySQL 表中检索数据的方法:

$this->query = "SELECT _id, name, price, creationDate, isPublished FROM fruits";
$this->fetch_type = PDO::FETCH_ASSOC;
$this->result = $db->query($this->query);
$this->rows = $this->result->fetchAll($this->fetch_type);
$this->columns = empty($this->rows) ? array() : array_keys($this->rows[0]);

这样我可以轻松地将列名存储在数组中(这正是我需要的):

var_dump($this->columns):

array
  0 => string '_id' (length=3)
  1 => string 'name' (length=4)
  2 => string 'price' (length=5)
  3 => string 'creationDate' (length=12)
  4 => string 'isPublished' (length=11)

但是,如果 fetch 类型为 ,我的方法不起作用PDO::FETCH_OBJ,因为我不再使用 2D 数组,而是使用数组中的对象:

var_dump($this->rows):

array
 0 => 
object(stdClass)[11]
  public '_id' => string '1' (length=1)
  public 'name' => string 'apple' (length=5)
  public 'price' => string '26.00' (length=5)
  public 'creationDate' => string '0000-00-00 00:00:00' (length=19)
  public 'isPublished' => string '1' (length=1)
 1 => 
object(stdClass)[12]
  public '_id' => string '2' (length=1)
  public 'name' => string 'banana' (length=11)
  public 'price' => string '15.00' (length=5)
  public 'creationDate' => string '0000-00-00 00:00:00' (length=19)
  public 'isPublished' => string '1' (length=1)
 2 => 
object(stdClass)[13]
  public '_id' => string '3' (length=1)
  public 'name' => string 'orange' (length=6)
  public 'price' => string '12.12' (length=5)
  public 'creationDate' => string '0000-00-00 00:00:00' (length=19)
  public 'isPublished' => string '1' (length=1)

  etc...

那么,如何从上述结果中获取列名?

4

2 回答 2

5

对此的简单答案是将传递给的项目强制转换array_keys()显式(array)- 这样,数组不受影响,但对象成为正确的类型:

$this->columns = empty($this->rows) ? array() : array_keys((array) $this->rows[0]);
于 2012-05-29T12:27:26.837 回答
4

getColumnMeta可以检索列的名称,它返回一个关联数组,其中包含明显的“名称”键。

所以

$meta = $this->result->getColumnMeta(0); // 0 indexed so 0 would be first column
$name = $meta['name'];
于 2012-05-29T12:31:51.763 回答