在PHP中从MySQL合并JSON数组查询结果

inkz8wg9  于 11个月前  发布在  Mysql
关注(0)|答案(2)|浏览(125)

现有的代码看起来像这样:

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数据以具有半类别?

fivyi3re

fivyi3re1#

只需在while循环中转换数组即可。

while($row = $result->fetch_assoc()) {
    $emptyArray[$row['name']]['name'] = $row['name'];
    $emptyArray[$row['name']]['skills'][$row['skill']] = $row['skill_score'];
  }

字符串

6l7fqoea

6l7fqoea2#

代替在最终阵列上应用json_encode

  • 应用于行
  • 连接所有行
  • 插入最后的连接字符串到数组中

这可能会解决这个问题

相关问题