如何使用mysqli group_concat创建嵌套JSON?

时间:2019-03-31 15:03:12

标签: php mysql arrays json mysqli

从嵌套JSON数据中提取值!

$response = array();
$result = mysqli_query($conn, "
    SELECT id, GROUP_CONCAT(CONCAT_WS(':', Name) SEPARATOR ',') AS Result 
    FROM mytbl GROUP BY id
");
mysqli_num_rows($result);
if(mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
        $char = array("id"=>$row["id"], "char"=>[$row["Result"]]);
        array_push($response,array('Attr'=>$char));
    }
}
echo json_encode($response);

我添加了我需要的照片

{{3}}

1 个答案:

答案 0 :(得分:0)

只需用PHP爆炸

$response = array();
$result =mysqli_query($conn, "

SELECT id, GROUP_CONCAT(CONCAT_WS(':', Name) SEPARATOR ',') AS Result 
FROM mytbl GROUP BY id ");
mysqli_num_rows($result);

if(mysqli_num_rows($result) > 0){
  while($row = mysqli_fetch_assoc($result)){
    $char = array("id"=>$row["id"],"char"=>explode(',', $row["Result"]));
    array_push($response,array('Attr'=>$char));
  }
}