44

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?

0

3 Answers 3

95

Is this what you want?

echo json_encode($artists)

PHP: json_encode

2
  • 1
    Thank you! 2020 and I didn't know you could just json_encode any php object into a json string. Feb 24, 2020 at 6:05
  • strange. print_r($myArray); gives me the whole structure of the array and its values.. but echo json_encode($myArray); just prints: [{},{},{}] empty objects.
    – Suisse
    Nov 7, 2022 at 10:10
2

The print_r have second parameter.


$string=print_r($array, true);

1

You can use this simple function from my CMS EFFCORE:

function data_stringify($data) {
  switch (gettype($data)) {
    case 'string' : return '\''.addcslashes($data, "'\\").'\'';
    case 'boolean': return $data ? 'true' : 'false';
    case 'NULL'   : return 'null';
    case 'object' :
    case 'array'  :
      $expressions = [];
      foreach ($data as $c_key => $c_value) {
        $expressions[] = data_stringify($c_key).' => '.
                         data_stringify($c_value);
      }
      return gettype($data) === 'object' ?
        '(object)['.implode(', ', $expressions).']' :
                '['.implode(', ', $expressions).']';
    default: return (string)$data;
  }
}

TEST

var_dump( data_stringify(-1    ) === '-1'     );
var_dump( data_stringify(-1.1  ) === '-1.1'   );
var_dump( data_stringify(123e1 ) === '1230'   ); # exponential notation
var_dump( data_stringify(0x123 ) === '291'    ); # hexadecimal notation
var_dump( data_stringify(01234 ) === '668'    ); # octal notation
var_dump( data_stringify(0b101 ) === '5'      ); # binary notation
var_dump( data_stringify('а123') === "'а123'" );
var_dump( data_stringify('123а') === "'123а'" );
var_dump( data_stringify(true  ) === 'true'   );
var_dump( data_stringify(false ) === 'false'  );
var_dump( data_stringify(null  ) === 'null'   );

array

var_dump(
  data_stringify([
    100,
   '200',
   'item3' =>  300,
   'item4' => '400',
   'item5' => 'value500'
  ]) === "[".
   "0 => 100, ".
   "1 => '200', ".
   "'item3' => 300, ".
   "'item4' => '400', ".
   "'item5' => 'value500']"
);

object

var_dump(
  data_stringify((object)[
    'prop1' =>  100,
    'prop2' => '200',
    'prop3' => 'value300'
  ]) === "(object)[".
   "'prop1' => 100, ".
   "'prop2' => '200', ".
   "'prop3' => 'value300']"
);

array with object

var_dump(
  data_stringify([
    100,
   '200',
   'item3' => (object)['prop1' =>  1, 'prop2' => '2', 'prop3' => 'value3'],
   'item4' => '400',
   'item5' => 'value500'
  ]) === "[".
   "0 => 100, ".
   "1 => '200', ".
   "'item3' => (object)['prop1' => 1, 'prop2' => '2', 'prop3' => 'value3'], ".
   "'item4' => '400', ".
   "'item5' => 'value500']"
);

object with array

var_dump(
  data_stringify((object)[
    'prop1' =>  1,
    'prop2' => '2',
    'prop3' => [100, '200', 'item3' => '300', 'item4' => 'value400'],
    'prop4' => 'value4'
  ]) === "(object)[".
   "'prop1' => 1, ".
   "'prop2' => '2', ".
   "'prop3' => [0 => 100, 1 => '200', 'item3' => '300', 'item4' => 'value400'], ".
   "'prop4' => 'value4']"
);

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.