【发布时间】:2014-01-04 02:06:31
【问题描述】:
我有一组来自 mysql 查询的数据,如下所示
hub | month | frequency
GALAXY | 10 | 1
GALAXY | 11 | 2
GALAXY | 12 | 1
LEVERAGES | 10 | 3
LEVERAGES | 12 | 2
我想使用 json_encode 将数据填充为 json 格式:
[{"name":"GALAXY","total":"4","articles":[["10","1"],["11","2"],["12","1"]]},{"name":"LEVERAGES","total":"5","articles":[["10","3"],["12","2"]]}]
但我无法获得正确的 json。以下是我的代码:
$root = array();
$aColumns = array('hub', 'month', 'frequency');
$tangos = $this->Report_Model->getMonthHubTango();
foreach($tangos->result_array() as $aRow)
{
$row = array();
$total = 0;
foreach($aColumns as $col)
{
$row[] = $aRow[$col];
$total += $aRow['frequency'];
$hub = $aRow['hub'];
}
$main['name'] = $hub;
$main['total'] = $total;
$main['articles'][] = $row;
}
$root[] = $main;
echo json_encode($root);
有人吗?提前谢谢..
【问题讨论】:
-
你的代码中
$hub在哪里定义? -
看起来
$main['name']和其他两个$main被每一次foreach迭代覆盖,所以你只会得到最后一次迭代结果到你的$root[]