以PHP代码的形式输出/打印数组。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了以PHP代码的形式输出/打印数组。相关的知识,希望对你有一定的参考价值。

Prints an array (recursive) as php code (can be pasted into a php file and it will work).

Note: This function can process arrays with integers/strings/sub-arrays. It is impossible to process resources (they have a state), and while it is possible to process objects, I didn't see a need for it. However, if you need it to support objects as well, I'll be more than happy to alter the function. Just drop a comment to let me know.
  1. /**
  2.  * Print an array (recursive) as PHP code (can be pasted into a php file and it will work).
  3.  * @param array $array
  4.  * @param boolean $return (whether to return or print the output)
  5.  * @return string|boolean (string if $return is true, true otherwise)
  6.  */
  7. function printArrayAsPhpCode($array, $return = false) {
  8. if (count($array) == 0) {
  9. if (!$return) {
  10. print "array()";
  11. return true;
  12. } else {
  13. return "array()";
  14. }
  15. }
  16. $string = "array(";
  17. if (array_values($array) === $array) {
  18. $no_keys = true;
  19. foreach ($array as $value) {
  20. if (is_int($value)) {
  21. $string .= "$value, ";
  22. } elseif (is_array($value)) {
  23. $string .= printArrayInPHPFormat($value, true) . ", ";
  24. } elseif (is_string($value)) {
  25. $string .= "$value', ";
  26. } else {
  27. trigger_error("Unsupported type of $value, in index $key.");
  28. }
  29. }
  30. } else {
  31. $string .=" ";
  32. foreach ($array as $key => $value) {
  33. $no_keys = false;
  34. if (is_int($value)) {
  35. $string .= ""$key" => $value, ";
  36. } elseif (is_array($value)) {
  37. $string .= ""$key" => " . printArrayInPHPFormat($value, true) . ", ";
  38. } elseif (is_string($value)) {
  39. $string .= ""$key" => '$value', ";
  40. } else {
  41. trigger_error("Unsupported type of $value, in index $key.");
  42. }
  43. }
  44. }
  45. $string = substr($string, 0, strlen($string) - 2); # Remove last comma.
  46. if (!$no_keys) {
  47. $string .= " ";
  48. }
  49. $string .= ")";
  50. if (!$return) {
  51. print $string;
  52. return true;
  53. } else {
  54. return $string;
  55. }
  56. }

以上是关于以PHP代码的形式输出/打印数组。的主要内容,如果未能解决你的问题,请参考以下文章

将数组打印为代码

PHP中遍历二维数组—以不同形式的输出操作

php中echoprintprint_rvar_dumpvar_export区别

为啥此代码片段返回意外结果?

php Yoast SEO规范输出的代码片段

php Yoast SEO规范输出的代码片段