PHP 数组字符串化

PHP array stringify

在我编写的歌词应用程序中,我使用数组打印艺术家 table。艺术家数组如下所示:

$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() 方式打印数组?

这是你想要的吗?

echo json_encode($artists)

PHP: json_encode

您可以使用我的 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;
  }
}

测试

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'   );

数组

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

对象

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

带对象的数组

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']"
);

带数组的对象

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']"
);