将MySQLI fetch_assoc()压缩为每列一个数组

时间:2013-05-24 09:21:31

标签: php mysql json mysqli

感谢Detect data type while using fetch_array with MySQLiOutput a property with PHP5 and method chaining,我可以使用MySQLi和方法链接在MySQL查询中填充json对象。

  /// Populate an array with the results;
  public function populate(){
    ($rows=array());

    while($row=$this->result->fetch_assoc())
      $rows[]=$row;

    $this->rows=$rows;

    $this->last=$this->rows;
    return $this;
  }

我获得了

[
  {
      "id": 1,
      "datein": "2012-06-06 09:59:05"
  },
  {
      "id": 2,
      "datein": "2012-06-06 11:32:45"
  },
  {
      "id": 3,
      "datein": "2012-06-07 00:47:19"
  }
]

我怎样才能获得

{
  "id": [1,2,3]
  "datein": ["2012-06-06 09:59:05","2012-06-06 11:32:45","2012-06-07 00:47:19"]
}

为了获得结果的替代和紧凑版本?

非常感谢你的帮助!

修改 感谢您的帮助,我准备了这种mysql包装器,并提供了两种获取方法: http://ross.iasfbo.inaf.it/~gloria/decibel-class

2 个答案:

答案 0 :(得分:1)

只需初始化数组,其中包含2个数组,其中一个用于保留id另一个用于保留datein

public function populate(){
$rows = array('id'=>array(), 'datein'=>array());

while($row=$this->result->fetch_assoc())
  $rows['id'][] = $row['id'];
  $rows['datein'][] = $row['datein'];

$this->rows = $rows;

$this->last = $this->rows;
return $this;

}

答案 1 :(得分:1)

您可以将代码更改为:

/// Populate an array with the results;
public function populate() {
    $rows = array();

    $this->result = array();
    while ($row = $this->result->fetch_assoc())
        foreach ($row as $field => $value)
            $this->result[$field][] = $value;

    return $this;
}