我正在为我的问题寻找解决方案。
我有以下代码:
while($row = mysql_fetch_array($resultQuery)){
$response = array(
'name' => $row['name'],
'data' => $row['data']
);
$responses[] = $response;
}
echo json_encode($responses);
代码将带来这个结果:
[{"name":"Name001","data":"1"},
{"name":"Name001","data":"2"},
{"name":"Name001","data":"3"},
{"name":"Name002","data":"4"},
{"name":"Name002","data":"5"},
{"name":"Name002","data":"6"}]
但我希望得到以下结果:
[{"name":"Name001","data":[1,2,3]},
{"name":"Name002","data":[4,5,5]}
每个"姓名"有自己的ID,我想在" while"把每个id都有自己的数据。
感谢您的帮助。
$id_name = "xx";
while($row = mysql_fetch_array($resultQuery)){
if($id !== $row['id']){
$response = array(
'name' => $row['name'],
'data' => array($row['data'])
);
$responses[] = $response;
}
$id_name = $row['id'];
}
echo json_encode($responses);
我首先要检查ID,如果不同会给我带来:
[{"name":"Name001","data":["1"]},{"name":"Name002","data":["4"]}]
答案 0 :(得分:0)
while($row = mysql_fetch_array($resultQuery))
$tmp[$row['name']][] = $row['data'];
foreach($tmp as $key => $item)
$responses[] = array('name' => $key, 'data' => $item);
echo json_encode($responses);
结果
[{"name":"Name001","data":["1","2","3"]},{"name":"Name002","data":["4","5","6"]}]
答案 1 :(得分:-1)
我在这里做了一个测试,希望你喜欢。
$arr = array();
$arr[] = array(
'name' => 'val',
'data' => array(1, 2, 3)
);
$arr[] = array(
'name' => 'val',
'data' => array(1, 2, 3)
);
echo json_encode($arr);
输出:
[{"name":"val","data":[1,2,3]},{"name":"val","data":[1,2,3]}]