-1

感谢Detect data type while using fetch_array with MySQLi and Output 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

4

2 回答 2

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;
}
于 2013-05-24T09:27:43.873 回答
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;
}
于 2013-05-24T09:27:56.567 回答