How to json_encode php array but the keys without quotes

后端 未结 5 1360
半阙折子戏
半阙折子戏 2020-12-06 04:52

I\'m trying to plot (with Flot) a pie chart with some data

var data = 

The result I get from that is t

5条回答
  •  自闭症患者
    2020-12-06 05:05

    I created a class to format json with php without quotes on the keys here is it

    class JsonFormatter
    {
    static $result = '';
    static $separator = '';
    
    public static function iterateArray($data) : string
    {
        static::$result .= '[';
        static::$separator = '';
        foreach ($data as $key => $val) {
            if (is_int($val)) {
    
            } elseif (is_string($val)) {
                static::$result .= '"' . str_replace('"', '\"', $val) . '"';
            } elseif (is_bool($val)) {
                static::$result .= $val ? 'true' : 'false';
            } elseif (is_object($val)) {
                static::iterateObject($val);
                static::$result .= ', ';
            } elseif (is_array($val)) {
                static::iterateArray($val);
                static::$result .= ', ';
            } else {
                static::$result .= $val;
            }
            if (!is_int($val)) {
                static::$separator = ', ';
            }
        }
    
        static::$result .= ']';
        return static::$result;
    }
    
    public static function iterate($data)
    {
        if (is_array($data)) {
            static::iterateArray($data);
        } elseif (is_object($data)) {
            static::iterateObject($data);
        }
        return static::$result;
    }
    
    public static function iterateObject($data)
    {
        static::$result .= '{';
        static::$separator = '';
        foreach ($data as $key => $val) {
    
            static::$result .= static::$separator . $key . ':';
    
            if (is_int($val)) {
                static::$result .= $val;
            } elseif (is_string($val)) {
                static::$result .= '"' . str_replace('"', '\"', $val) . '"';
            } elseif (is_bool($val)) {
                static::$result .= $val ? 'true' : 'false';
            } elseif (is_object($val)) {
                static::iterate($val, true);
                static::$result .= ', ';
            } elseif (is_array($val)) {
                static::iterateArray($val, true);
                static::$result .= ', ';
            } else {
                static::$result .= $val;
            }
            static::$separator = ', ';
        }
        static::$result .= '}';
        return static::$result;
    }
    
    }
    

    you can now call

    $jsonWithoutKeyQuotes  = JsonFormatter::iterate($data);
    

    thanks to Marcin Orlowski

提交回复
热议问题