php数组格式化输出为代码

代码

<?php

class ArrayHelpers
{
    public static function isIndexed($array, $consecutive = false)
    {
        if (!is_array($array)) {
            return false;
        }

        if (empty($array)) {
            return true;
        }

        if ($consecutive) {
            return array_keys($array) === range(0, count($array) - 1);
        }

        foreach ($array as $key => $value) {
            if (!is_int($key)) {
                return false;
            }
        }

        return true;
    }
    public static function getTabs($num){
        $tabs = "";
        for ($i = 1;$i <= $num;$i++){
            $tabs .= "    ";
        }
        return $tabs;
    }

    protected static function echoArrayContent(array $array,$tabs = 2){
        $tabs++;
        foreach ($array as $key => $item){
            if (is_array($item)){
                if (static::isIndexed($item)){ //索引数组
                    echo static::getTabs($tabs) . '"' . $key . '" => ' . "[";
                    foreach ($item as $k => $v){
                        echo (is_numeric($v) ? $v : '"' . $v . '"');
                        if ($k != count($item) - 1){echo ",";}
                    }
                    echo "]\r\n";
                }else{ //关联数组
                    echo static::getTabs($tabs) . '"' . $key . '" => [' . "\r\n";
                    static::echoArrayContent($item,$tabs);
                    echo static::getTabs($tabs) . "],\r\n";
                }
            }else{
                $val = is_numeric($item) ? $item : '"' . $item . '"';
                echo static::getTabs($tabs) . '"' . $key . '" => ' . $val . ",\r\n";
            }
        }
    }

    public static function getArrayContent(array $array,$tabs = 2){
        ob_start();
        static::echoArrayContent($array,$tabs-1);
        return ob_get_clean();
    }
}

测试

$arr = ["a" => 111,"b"=>2,"c" => ["d" => 12,"e" => ["f" => "aa","e" => "ttt"]],"d" => ["s" => 1]];

$content = ArrayHelpers::getTabs(1) . "return [\r";

$content .= ArrayHelpers::getArrayContent($arr);

$content .= ArrayHelpers::getTabs(1) . "];";

file_put_contents('./text.txt',$content);

输出结果

posted @ 2021-01-04 04:16  huaanhuang  阅读(225)  评论(0编辑  收藏  举报