php 到 json 组数组

php to json group array

我的目标是列出歌手并点击歌手显示歌手的歌曲。 这是我的 php

<?php
    $server = "localhost";
    $username = "user";
    $password = "123456";
    $database = "database";
    $con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
    mysql_select_db($database, $con);
    mysql_query("set names 'utf8'");
    $sql = "SELECT a.singername,b.songname,b.songembeded from singers a,songs b where a.singerid=b.singerid";
    $result = mysql_query($sql) or die ("Query error: " . mysql_error());
    $records = array();
    while($row = mysql_fetch_assoc($result)) {
        $records[] = $row;
    }
    mysql_close($con);
    utf8_encode($records);
    echo json_encode($records);
?>

这是我的 json 输出:

[{"singername":"singerA", "songname":"songA", "songembeded":"https://www.youtube.com"},{"singername":"singerA", "songname":"songB", "songembeded":"https://www.youtube.com"}, "singername":"singerB","songname":"songX", "songembeded":"https://www.youtube.com"}]

我想做一个喜欢组合的歌手和他们的歌:

["singername":"singerA","songs": {"songname":"songA","songembeded":"https://www.youtube.com"},{"songname":"songB","songembeded":"https://www.youtube.com"},
"singername":"singerB","songs": {"songname":"songX","songembeded":"https://www.youtube.com"}]

稍微更改您的查询:

$sql = "SELECT a.singername,b.songname,b.songembeded from singers a,songs b where a.singerid=b.singerid ORDER BY a.singername";

所以替换你的循环:

$records = array();
    while($row = mysql_fetch_assoc($result)) {
        $records[] = $row;
    }

用这个

$records = array();
$songs= array();
$singername='';
while($row = mysql_fetch_assoc($result)) {

    if ($singername!='' && $singername!=$row['singername']) {
       $records[]= array("singername"=>$singername,"songs"=>$songs);
       $songs = array();
    }
    $songs[] = array('songname'=>$row['songname'],'songembeded'=>$row['songembeded']);
    $singername=$row['singername'];
}
$records[]= array("singername"=>$singername,"songs"=>$songs);