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);
相关推荐
2601_961875243 小时前
法考考试时间安排及科目|时间表|资料已整理
开发语言·c#·inverted-index·suffix-tree·sstable·r-tree·lsm-tree
AI科技星3 小时前
数术工坊第八卷:算力革命
c语言·开发语言·网络·量子计算·agi
geovindu3 小时前
go: Generators Pattern
开发语言·后端·设计模式·golang·生成器模式
码云骑士4 小时前
13-列表append的底层真相(上)-listobject源码中的预分配策略
开发语言·python
.道阻且长.5 小时前
C++ string 操作指南:接口解析
java·c语言·开发语言·c++
蚰蜒螟5 小时前
Java 对象的内存密语:从字段偏移量计算到 Unsafe 访问的完整链路
java·开发语言
星辰_mya5 小时前
CountDownLatch深度解析
java·开发语言·后端·架构
laplaya5 小时前
使用 vcpkg 管理 C++ 项目中的依赖
开发语言·c++
feixing_fx6 小时前
选择器的威力——深入理解优先级计算与层叠规则
开发语言·前端·css·前端框架·html
6v6-博客6 小时前
C语言字符串中空格的表示方法
c语言·开发语言