在我编写的歌词应用程序中,我使用数组来打印艺术家表。艺术家阵列看起来像这样:
$artists = [
[ "Avril Lavigne" ],
[ "3 Doors Down" ],
[ "Celine Dion" ],
[ "Evanescence" ],
[ "Shania Twain" ],
[ "Green Day" ],
//...
];
在打印之前,我对阵列进行了一些修改。我有一个包含歌词文件的每个艺术家的文件夹。我将文件夹名称添加到$artists
数组中供以后使用:
$folder_fix = [
[" ", "_" ],
[".", "" ],
["&", "n" ],
];
for ($i = 0; $i < count($artists); $i++) {
$folder_name = strtolower($artists[$i][0]);
for ($k = 0; $k < count($folder_fix); $k++) {
$folder_name = str_replace($folder_fix[$k][0], $folder_fix[$k][1], $folder_name);
}
array_push($artists[$i], $folder_name);
}
稍后,我将每个艺术家的专辑和曲目数添加到数组中:
$lyrics_base = "lyrics/";
for ($i = 0; $i < count($artists); $i++) {
$albums_path = $lyrics_base . $artists[$i][1] . "/*";
$tracks_path = $lyrics_base . $artists[$i][1] . "/*/*";
$albums = count(glob($albums_path));
$tracks = count(glob($tracks_path));
array_push($artists[$i], $albums);
array_push($artists[$i], $tracks);
}
数组的最终结果如下所示:
$artists = [
[ "Avril Lavigne", "avril_lavigne", 5, 61 ],
[ "3 Doors Down", "3_doors_down", 5, 13 ],
[ "Celine Dion", "celine_dion", 7, 22 ],
[ "Evanescence", "evanescence", 4, 10 ],
[ "Shania Twain", "shania_twain", 3, 12 ],
[ "Green Day", "green_day", 8, 26 ],
//...
];
现在,我的问题是每次访问页面时都会发生此过程。第二,第三和第四列一次又一次地创建。我认为这是多余的。
我想保存数组的最终结果并在页面上使用它。如果这是JavaScript,我会使用JSON.stringify()
,但在PHP中,我不知道如何获得数组的最终结果。 print_r()
没有完成这项工作,因为它会像这样打印出来:
Array
(
[0] => Array
(
[0] => Avril Lavigne
[1] => avril_lavigne
[2] => 5
[3] => 61
)
[1] => Array
(
[0] => 3 Doors Down
[1] => 3_doors_down
[2] => 5
[3] => 13
)
...
我想这样:
[
[
"Avril Lavigne",
"avril_lavigne",
5,
61
],
[
"3 Doors Down",
"3_doors_down",
5,
13
],
//...
]
有没有办法以JSON.stringify()
方式打印数组?