【问题标题】:Compact a MySQLI fetch_assoc() to one array per column将 MySQLI fetch_assoc() 压缩为每列一个数组
【发布时间】:2013-05-19 20:30:00
【问题描述】:

感谢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

【问题讨论】:

  • 您会发现您的第一个版本更好并且更易于使用。我反对你的想法。
  • 感谢您的建议。事实上我会有这两种方法,我可以根据情况使用其中一种。
  • 无论如何,因为我询问了另一种获取数据的方法而对我投了反对票,这有点奇怪:|
  • 我认为反对票是因为您没有严格尝试达到您想要的结果,但是这个问题看起来像是一个经过适当伪装的“给我代码”问题。恕我直言,我没有对你投反对票。

标签: php mysql json mysqli


【解决方案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;
}

【讨论】:

    【解决方案2】:

    您可以将代码更改为:

    /// 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-06
      • 2010-11-07
      • 2016-07-22
      • 2011-11-25
      • 1970-01-01
      • 2021-12-26
      • 2011-06-17
      相关资源
      最近更新 更多