Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Mehrere MySQL-Tabellen in json_encode

Ok, ich habe deine Lösung aufgeschrieben. Sie müssen sicher sein, dass die Bestellung von dort enthalten ist, da davon ausgegangen wird, dass Sie sie mit ihren Artikeln zusammen bestellen. Ich wusste auch nicht, wie Ihr Verlag gespeichert wurde, also habe ich das in eine separate Tabelle aufgeteilt (dies ermöglicht es Ihnen, dann auch Artikel von genau diesem Verlag zu erhalten), die jetzt 4 Joins sind. Außerdem habe ich es aktualisiert, um auch innere Verbindungen herzustellen. Auf diese Weise erhalten Sie keine leeren Ergebnisse für Konsolen, denen keine Spiele zugewiesen sind. Wenn Sie diese möchten, können Sie einfach die Verknüpfungen so ändern, dass Sie auch diese Ergebnisse erhalten. Lassen Sie mich wissen, ob das hilft

//get all of the information
$query = '
    SELECT c.consoleId,c.consoleName,m.modelId,m.modelName,g.gameId,g.gameName,p.publisherId,p.publisherName
    FROM `consoleconsole` c
        INNER JOIN `consolemodel` m ON c.consoleId=m.consoleId
        INNER JOIN `consolegame` g ON m.modelId=g.modelId
        INNER JOIN `consolepublisher` p ON g.publisherId = p.publisherId
    ORDER BY c.consoleName, m.modelName, g.gameName
';

//get the results
$result = mysql_query($query);

//setup array to hold information
$consoles = array();

//setup holders for the different types so that we can filter out the data
$consoleId = 0;
$modelId = 0;

//setup to hold our current index
$consoleIndex = -1;
$modelIndex = -1;

//go through the rows
while($row = mysql_fetch_assoc($result)){
    if($consoleId != $row['consoleId']){
        $consoleIndex++;
        $modelIndex = -1;
        $consoleId = $row['consoleId'];

        //add the console
        $consoles[$consoleIndex]['console'] = $row['consoleName'];

        //setup the information array
        $consoles[$consoleIndex]['information'] = array();
    }

    if($modelId != $row['modelId']){
        $modelIndex++;
        $modelId = $row['modelId'];

        //add the model to the console
        $consoles[$consoleIndex]['information'][$modelIndex]['model'] = $row['modelName'];

        //setup the title array
        $consoles[$consoleIndex]['information'][$modelIndex]['title'] = array();
    }

    //add the game to the current console and model
    $consoles[$consoleIndex]['information'][$modelIndex]['title'][] = array(
        'game'      => $row['gameName'],
        'publisher' => $row['publisherName']
    );
}

echo json_encode($consoles);