现有的代码看起来像这样:
function getList(){
$sql = 'SELECT DISTINCT `person`.`person_name` as name, `skill`.`skill_name` as
skill,`skill_linker`.`skill_score`;
$result = $GLOBALS['conn']->query($sql);
if ($result->num_rows > 0) {
$emptyArray = array();
while($row = $result->fetch_assoc()) {
$emptyArray[] = $row;
}
echo json_encode($emptyArray);
}
}
字符串
JSON从上面的函数输出:
[{
"name":"Bob Sun",
"skill":"Dancing",
"skill_score":"3"
},
{
"name":"Bob Sun",
"skill":"Surfing",
"skill_score":"2"
},
{
"name":"Bob Sun",
"skill":"Swimming",
"skill_score":"5"
},
{
"name":"Joe Steel",
"skill":"Eating",
"skill_score":"2"
},
{
"name":"Joe Steel",
"skill":"Cooking",
"skill_score":"3"
}]
型
相反,我希望JSON输出看起来像这样:
[
{
"name": "Bob Sun",
"skills" : [
"Dancing": 3,
"Surfing": 2,
"Swimming": 5
]
},
{
"name": "Joe Steel",
"skills" : [
"Eating": 2,
"Cooking": 3
]
}
]
型
这可以做到吗?如果来自SQL结果集的数据是独立的,我如何让它为每个人显示skills:skill_score?我如何修改代码来重构JSON数据以具有半类别?
2条答案
按热度按时间fivyi3re1#
只需在while循环中转换数组即可。
字符串
6l7fqoea2#
代替在最终阵列上应用
json_encode
,这可能会解决这个问题