[ php ] json 출력시 한줄로 헛갈리는 부분을 배열로 잘보이게 하기 위한 함수, json 예쁘게 정렬 > php

본문 바로가기

사이트 내 전체검색

php

[ php ] json 출력시 한줄로 헛갈리는 부분을 배열로 잘보이게 하기 위한 함수, json 예쁘게 정렬

작성일 18-11-06 18:13

페이지 정보

작성자 웹지기 조회 9,068회 댓글 0건

본문

[code]

$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');

header('Content-type: text/javascript');

echo json_encode($data);

[/code]

다음과 같은 방식으로 출력됨

[code]

{"a":"apple","b":"banana","c":"catnip"}

[/code]


이를 예쁘게 정렬하려면

{

    "a": "apple",

    "b": "banana",

    "c": "catnip"

}


php 5.4 이상

JSON_PRETTY_PRINT 옵션을 추가한다.

pre와 함께 사용해야 코드가 예쁘게 출력된다.

[code]

$json_string = json_encode($data, JSON_PRETTY_PRINT);

echo "<pre>".$json_string."<pre><br>";

[/code]

php 5.4미만

사용자 함수를 이용한다

pre와 함께 사용해야 한다.

[code]

$json_string = prettyPrint(json_encode($data));

echo "<pre>".$json_string."<pre><br>";

function prettyPrint( $json )

{

    $result = '';

    $level = 0;

    $in_quotes = false;

    $in_escape = false;

    $ends_line_level = NULL;

    $json_length = strlen( $json );


    for( $i = 0; $i < $json_length; $i++ ) {

        $char = $json[$i];

        $new_line_level = NULL;

        $post = "";

        if( $ends_line_level !== NULL ) {

            $new_line_level = $ends_line_level;

            $ends_line_level = NULL;

        }

        if ( $in_escape ) {

            $in_escape = false;

        } else if( $char === '"' ) {

            $in_quotes = !$in_quotes;

        } else if( ! $in_quotes ) {

            switch( $char ) {

                case '}': case ']':

                    $level--;

                    $ends_line_level = NULL;

                    $new_line_level = $level;

                    break;


                case '{': case '[':

                    $level++;

                case ',':

                    $ends_line_level = $level;

                    break;


                case ':':

                    $post = " ";

                    break;


                case " ": case "\t": case "\n": case "\r":

                    $char = "";

                    $ends_line_level = $new_line_level;

                    $new_line_level = NULL;

                    break;

            }

        } else if ( $char === '\' ) {

            $in_escape = true;

        }

        if( $new_line_level !== NULL ) {

            $result .= "\n".str_repeat( "\t", $new_line_level );

        }

        $result .= $char.$post;

    }

    return $result;

}

[/code]


추천0

비추천 0

댓글목록

등록된 댓글이 없습니다.

전체 82건 1 페이지

이미지 목록

게시물 검색
Copyright © 즐거운 코딩 생활 ( funyphp ). All rights reserved.
PC 버전으로 보기