dqsvnsad79721 2014-01-04 02:06
浏览 67

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

I have a set of data from mysql query as per below

hub       | month | frequency 
GALAXY    | 10    | 1
GALAXY    | 11    | 2 
GALAXY    | 12    | 1 
LEVERAGES | 10    | 3 
LEVERAGES | 12    | 2 

and i would like to populate the data to json format using json_encode as this :

[{"name":"GALAXY","total":"4","articles":[["10","1"],["11","2"],["12","1"]]},{"name":"LEVERAGES","total":"5","articles":[["10","3"],["12","2"]]}]

But i couldn't get the right json. Below is my code:

$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);

Anyone? Thanks in advance..

  • 写回答

3条回答 默认 最新

  • dongquanlin1885 2014-01-04 02:13
    关注

    I think, you should add $root[] = $main; into foreach block, so every $main array will be put into $root matrix:

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

    Plus, you have $hub undefined in loop. So, $main['name'] will probably be undefined.

    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制