Skip to content
Advertisement

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"                   ],
    //...
];

Before printing it, I do some modification to the array. I have a folder for each artist that contains the lyrics files. I add the folder names to the $artists array for later use:

$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.

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
    ],
    //...
]

Is there a way to print the array the JSON.stringify() way?

Advertisement

Answer

Is this what you want?

echo json_encode($artists)

PHP: json_encode

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement