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);
相关推荐
天道有情战天下19 分钟前
python flask
开发语言·python·flask
帅弟1501 小时前
Day4 C语言与画面显示练习
c语言·开发语言
qhs15731 小时前
Kotlin字符串操作在Android开发中的应用示例
android·开发语言·kotlin
Stack Overflow?Tan902 小时前
c++实现在同一台主机两个程序实现实时通信
开发语言·c++
MZWeiei2 小时前
Scala:case class(通俗易懂版)
开发语言·后端·scala
闯闯桑2 小时前
scala 中的@BeanProperty
大数据·开发语言·scala
计算机老学长2 小时前
基于Python的商品销量的数据分析及推荐系统
开发语言·python·数据分析
MZWeiei2 小时前
scala有关 类 的知识点与Java的比较
开发语言·scala
&白帝&3 小时前
Java @PathVariable获取路径参数
java·开发语言·python