Я загрузил данные песни iTunes в базу данных MySQL, и я пытаюсь использовать PHP для получения информации о альбоме JSON. Этот код ..
<?php /* Connect to database */ require ('include/connect.php'); /* Build the query */ $query = "SELECT a.album,a.name,a.artist,a.year AS track_year, b.year AS album_year FROM staging a, (SELECT album, MAX(year) AS year FROM staging GROUP BY album) b WHERE a.album = b.album"; /* Loop through the results and build a JSON array for the data table */ $result = $mysqli->query($query); $info = array(); while ($row = $result->fetch_array(MYSQLI_ASSOC)) { if (!isset($info[$row['album']])) { $info[$row['album']] = array( 'record' => $row['album'] , 'artist' => $row['artist'] , 'year' => $row['album_year'] , 'tracks' => array() ); } $info[$row['album']]['tracks'][] = $row['name']; } $data = json_encode($info); ?>
производит этот результат (усекается до двух альбомов) …
{ "Abbey Road": { "album": "Abbey Road", "artist": "The Beatles", "year": "1969", "tracks": [ "Come Together", "Something", "Maxwell's Silver Hammer", "Oh! Darling", "Octopus's Garden", "I Want You (She's So Heavy)", "Here Comes The Sun", "Because", "You Never Give Me Your Money", "Sun King", "Mean Mr. Mustard", "Polythene Pam", "She Came In Through The Bathroom Window", "Golden Slumbers", "Carry That Weight", "The End", "Her Majesty" ] }, "Accelerate": { "album": "Accelerate", "artist": "REM", "year": "2008", "tracks": [ "Living Well Is the Best Revenge", "Man-Sized Wreath", "Supernatural Superserious", "Hollow Man", "Houston", "Accelerate", "Until the Day Is Done", "Mr. Richards", "Sing for the Submarine", "Horse to Water", "I'm Gonna DJ", "Supernatural Superserious (Live)" ] } }
Я бы хотел, чтобы мои результаты выглядели так …
[ { "album": "Abbey Road", "artist": "The Beatles", "year": "1969", "tracks": [ "Come Together", "Something", "Maxwell's Silver Hammer", "Oh! Darling", "Octopus's Garden", "I Want You (She's So Heavy)", "Here Comes The Sun", "Because", "You Never Give Me Your Money", "Sun King", "Mean Mr. Mustard", "Polythene Pam", "She Came In Through The Bathroom Window", "Golden Slumbers", "Carry That Weight", "The End", "Her Majesty" ] }, { "album": "Accelerate", "artist": "REM", "year": "2008", "tracks": [ "Living Well Is the Best Revenge", "Man-Sized Wreath", "Supernatural Superserious", "Hollow Man", "Houston", "Accelerate", "Until the Day Is Done", "Mr. Richards", "Sing for the Submarine", "Horse to Water", "I'm Gonna DJ", "Supernatural Superserious (Live)" ] } ]
Очевидно, я новичок в кодировании JSON с PHP. Что я делаю не так? Благодаря!
Вызовите array_values
в своем массиве:
$data = json_encode(array_values($info));
Это удаляет ваши именованные индексы и вместо них преобразует их в числовые, поэтому json_encode
должен обрабатывать ваш массив как индексированный (а не ассоциативный) массив.