获取sql结果作为嵌套的json对象

时间:2016-02-17 20:53:34

标签: javascript php arrays json ajax

通过while循环使用sql查询和group_concat,我实现了以下结果:

$rows[] = array('name' =>$row['customer'] , 'atw' =>$row['atw_number'] ,
     'dr' =>array(array('drnumber'=>(($row['dr_number'])),)),);

{       “名称”:“MULTIBUILD CORP”,       “atw”:“7146”,       “博士”:[         {           “drnumber”:“1608,1610,1611”         }       ]     },

相反,我可以有类似的东西:

{       “名称”:“MULTIBUILD CORP”,       “atw”:“7146”,       “博士”:[         {           “drnumber”:“1608”         },         {           “drnumber”:“1610”         },         {         “drnumber”:“1611”         }       ]     },

1 个答案:

答案 0 :(得分:1)

在while循环中,将当前$rows[] = ...替换为:

$numbers = [];
foreach (explode(',', $row['dr_number']) as $number)
    $numbers[] = ['dr_number' => $number];

$rows[] = array(
    'name' => $row['customer'],
    'atw' => $row['atw_number'],
    'dr' => $numbers
);