0

My goal is list singers and click singer show singers songs. This is my 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);
?>

This is my json output:

[{"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"}]

I want to make like a group singers and their songs:

["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"}]
6
  • The grouping you want would have duplicate keys. Commented Feb 20, 2015 at 19:19
  • We just don't do it like this any more Commented Feb 20, 2015 at 19:23
  • my singer table singerid,singername Commented Feb 20, 2015 at 19:29
  • my songs table songid,songname,songembeded,singerid... Commented Feb 20, 2015 at 19:30
  • relation two table singerid Commented Feb 20, 2015 at 19:30

1 Answer 1

1

Change your query a little:

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

so replace you loop:

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

with this one

$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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.