PHP:如何将Php数组转换为json格式

时间:2014-01-04 02:06:31

标签: php mysql arrays json

我有一组来自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);

任何?提前谢谢..

3 个答案:

答案 0 :(得分:0)

我认为,您应该将$root[] = $main;添加到foreach块中,因此每个$ main数组都将被放入$ root矩阵中:

foreach($tangos->result_array() as $aRow)

{
    $row = array();
    $total = 0;

    foreach($aColumns as $col)
    {
        $row[] = $aRow[$col];
        $total += $aRow['frequency'];

    }
    $main['name'] = $hub;
    $main['total'] = $total;
    $main['articles'][] = $row;                 
    $root[] = $main;
}

另外,你在循环中有$ hub undefined。因此,$ main ['name']可能未定义。

答案 1 :(得分:0)

$root = array();
$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'];

                        }
                        $main['name'] = $hub;
                        $main['total'] = $total;
                        $main['articles'][] = $row;                 
                        $root[] = $main;
                    }


echo json_encode($root);

答案 2 :(得分:0)

就像上面描述的那样,但是如果你想给根一个属性,这将允许你保持数据的组织。使用$root['data'] = $main;。因此代码将成为:

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['data'] = $main;
echo json_encode($root);