PHP数组字符串化 [英] PHP array stringify
问题描述
在歌词的应用程序,我编码,我使用一个数组来打印艺术家表。艺术家数组是这样的:
In a lyrics application I'm coding, I'm using an array to print an artists table. The artists array looks like this:
$artists = [
[ "Avril Lavigne" ],
[ "3 Doors Down" ],
[ "Celine Dion" ],
[ "Evanescence" ],
[ "Shania Twain" ],
[ "Green Day" ],
//...
];
在打印前,我做了一些修改阵列。我有一个包含歌词文件每个艺术家的文件夹。我添加的文件夹名称为 $艺术家
数组供以后使用:
$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);
}
后来,我添加专辑和曲目计数每个艺术家的数组:
Later, I add the album and track count for each artist to the array:
$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);
}
数组的最终结果是这样的:
The end result of the array looks like this:
$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 ],
//...
];
现在,我的问题是,这个过程发生我每次访问的页面的时间。第二,第三,和第四列被一次又一次地创建。我认为这是多余的。
Now, my problem is that this process happens every time I visit the page. The 2nd, 3rd, and the 4th columns are created again and again. I think this is redundant.
我要保存阵列的最终结果,并用它在页面上。如果这是JavaScript的我会使用 JSON.stringify()
,但在PHP中,我不知道如何获取数组的最终结果。 的print_r()
不会做的工作,因为它打印这样的:
I want to save the end result of the array and use it on the page. If this was JavaScript I'd use JSON.stringify()
, but in PHP I don't know how to get the end result of the array. print_r()
doesn't do the job, because it prints it like this:
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
)
...
我希望它是这样的:
I want it like this:
[
[
"Avril Lavigne",
"avril_lavigne",
5,
61
],
[
"3 Doors Down",
"3_doors_down",
5,
13
],
//...
]
有没有一种方法来打印数组 JSON.stringify()
办法?
推荐答案
这是你想要的吗?
回声json_en code($艺术家)
echo json_encode($artists)
这篇关于PHP数组字符串化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!