我最近构建了一个类,用于查询结果的自动分页和排序,该类可用于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...

那么,如何从上面这样的结果中获取列名呢?

最佳答案

简单的答案是cast传递给显式array_keys()的项-这样,数组不受影响,但对象成为正确的类型:

$this->columns = empty($this->rows) ? array() : array_keys((array) $this->rows[0]);

关于php - 如何从PDOStatement获取列名?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10799062/

10-14 13:06