gpt4 book ai didi

php - 来自 PHP 数组的嵌套 JSON

转载 作者:行者123 更新时间:2023-11-29 02:27:46 25 4
gpt4 key购买 nike

我已将我的 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": "R.E.M.",
"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": "R.E.M.",
"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)"
]
}
]

很明显,我不熟悉使用 PHP 对 JSON 进行编码。我究竟做错了什么?谢谢!

最佳答案

调用array_values在你的阵列上:

$data = json_encode(array_values($info));

这会删除您的命名索引并将它们转换为数字索引,因此 json_encode 应该将您的数组视为索引(而不是关联)数组。

关于php - 来自 PHP 数组的嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18474814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com