There are 3 arrays in my PHP, $console, $model, and $game.
Here is the code by the way:
<?PHP
$console = array();
$model = array();
$game = array();
$gameQuery = "SELECT * FROM consoleGame";
$gameResult = mysql_query($gameQuery) or die(mysql_error());
while ($row = mysql_fetch_assoc($gameResult)) {
if(!is_array($game[$row['modelId']])) {
$game[$row['modelId']] = array();
}
$game[$row['modelId']][$row['gameId']] = array(
'Game Name' => $row['gameName'],
'Game ID' => $row['gameId']);
}
$modelQuery = "SELECT * FROM consoleModel";
$modelResult = mysql_query($modelQuery) or die(mysql_error());
while ($row = mysql_fetch_assoc($modelResult)) {
if (!is_array($model[$row['consoleId']])) {
$model[$row['consoleId']] = array();
}
$model[$row['consoleId']][$row['modelId']] = array(
'Model Name' => $row['modelName'],
'Model ID' => array_values($game[$row['modelId']])); //This is the warning by the way.
}
$consoleQuery = "SELECT * FROM consoleConsole";
$consoleResult = mysql_query($consoleQuery) or die(mysql_error());
while ($row = mysql_fetch_assoc($consoleResult)) {
if (!is_array($console[$row['consoleId']])) {
$console[$row['consoleId']] = array();
}
$console[$row['consoleId']] = array(
'Console Name' => $row['consoleName'],
'Console ID' => array_values($model[$row['consoleId']]));
}
$console = array_values($console);
echo json_encode($console);
?>
As you can see in the code, I have added array_values to $console and $model without a hitch. I was lucky back then. When I added array_values to $game, it creates a warning. What is the possible fix to this?
Additional information
I declared $console, $model and $game as an array(). I have no idea why it’s not shown above $gameQuery.
You’re using three different queries to get results from your database, and although you ‘check’ if a key is present for the ‘modelId’ in the $game array, it is possible that no game exists for a specific model;
This line guarantees that a key is added to the $game array if that modelId was not yet present
However, in the second loop, with results from
SELECT * FROM consoleModelyour loading all models, possibly some have no games in your database, so there won’t be a key for that modelId in the $game array.For example:
consoleGame
consoleModel
This will have 2 games for ModelA, but none for ModelB.
You may work around this issue by adding this inside the
$modelResultloop tooSome ideas
The way you’re collecting the data doesn’t really use the ‘power’ of the database. Databases are designed to retrieve data and related data (hence the name ‘relational database’)
For example, to collect all consoleModels, including the games for that model (if any) use this;
Which will return;
Although this will duplicate the ModelName rows, it may make things easier for you, as you won’t have to run 3 separate loops.
Mode optimized options will be possible (e.g. loop through all consoleModels in PHP and collect the related games inside the loop), I will leave that up to you to try and learn