Codeigniter在foreach循环中组合了两个数组

时间:2017-12-02 19:41:03

标签: php arrays codeigniter

我有两个数组合的问题,这里是我的示例代码

$arr1 = [];
$data = $this->db->query("SELECT QUERY");

foreach ($data->result_array() as $row) {

$arr1[] = array(
   "type"                   => "column",
   "name"                   => $row['name'],
   "legendText"             => $row['name'],
   "showInLegend"           => true
);

}


$count = $this->db->query("SELECT QUERY");

foreach ($count->result_array() as $rows) {

$arr1[]["dataPoints"] = array(
   "label" => $rows['data']
);

}

使用此代码,结果为

[
  {
    "type": "column",
    "name": "LA 1",
    "legendText": "LA 1",
    "showInLegend": true
  },
  {
    "dataPoints": {
      "label": "1"
    }
  }
]

我想组合两个数组,所以输出应该是这样的:

[
  {
    "type": "column",
    "name": "LA 1",
    "legendText": "LA 1",
    "showInLegend": true,
    "dataPoints": [{
      "label": "1"
    }]
  }
]

请有人帮我找出解决此问题的最简单方法。

1 个答案:

答案 0 :(得分:2)

解决此问题的正确方法是将数据库查询更改为将在单个查询中返回所有信息的查询。

$data = $this->db->query("SELECT a.*, b.datapoints FROM table1 a, table2 b....");