PHP:格式化JSON为PHP语法格式

  1. 原生函数
php 复制代码
$arr = [1,2,3,4];
$str = var_export($a,true);
var_dump($str);
  1. 自定义方法
php 复制代码
class Export{
  private static $space;
  private static function do($a, string $prev){
    $res = '';
    $next = $prev . self::$space;
    if (is_array($a)) {
      $res .= '[';
      foreach ($a as $k => $v)  if (is_int($k)) {
        $res .= $next . self::do($v, $next) . ',';
      } else {
        $res .= $next . self::do($k, $next) . ' => ' . self::do($v, $next) . ',';
      }
      return $res . $prev . ']';
    } else if (is_scalar($a)) {
      return is_string($a) ? '\'' . str_replace('\'', '\\\'', $a) . '\'' : json_encode($a);
    } else return 'NULL';
  }
  public static function to($a, int $space_len = 2){
    self::$space = str_repeat(' ', max($space_len, 2));
    return self::do($a, PHP_EOL);
  }
}

// $str = Export::to(转化的数据);
// var_dump($str);
相关推荐
flying robot41 分钟前
js在浏览器执行原理
开发语言·javascript·ecmascript
dhxhsgrx4 小时前
PYTHON训练营DAY25
java·开发语言·python
风逸hhh6 小时前
python打卡day25@浙大疏锦行
开发语言·python
刚入门的大一新生6 小时前
C++初阶-string类的模拟实现与改进
开发语言·c++
chxii8 小时前
5java集合框架
java·开发语言
老衲有点帅8 小时前
C#多线程Thread
开发语言·c#
C++ 老炮儿的技术栈8 小时前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
IsPrisoner8 小时前
Go语言安装proto并且使用gRPC服务(2025最新WINDOWS系统)
开发语言·后端·golang
Python私教8 小时前
征服Rust:从零到独立开发的实战进阶
服务器·开发语言·rust