웹프로그래밍

Global It Leader!!


PHP


 
 

PHP 에서 json 형식의 다차원 배열 값 읽고 출력하기

페이지 정보

작성자 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 댓글 0건 조회 3,445회 작성일 22-03-26 17:26

본문

PHP 에서 JSON 데이터를 파싱하는 방법이다.

JSON 데이터는 Local File 을 읽어오는 것과 Web 사이트에서 해당 URL 을 읽어오는 방법이 있다.

가장 먼저 파싱해야 할 데이터 형태 파악을 하는 코드부터 살펴보고자 구글링을 했더니 관련 코드가 있어서 주석을 좀 더 추가하고 이해를 돕는 걸 첨가하여 적어둔다.

 

 <?php
// Web JSON 파일 읽어오기
$url = 'http://ip주소/getFileList.php';
$json_string = file_get_contents($url);

// Local JSON 파일 읽어오기
//$json_string = file_get_contents('weather.json');
// 다차원 배열 반복처리
$R = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json_string, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);
// $R : array data
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.

foreach ($R as $key => $val) {
    if(is_array($val)) { // val 이 배열이면
        echo "$key:<br/>";
        //echo $key.' (key), value : (array)<br />';
    } else { // 배열이 아니면
        echo "$key => $val <br />";
    }
}
?>

 

위 코드로 형태파악을 한 다음에 필요한 것을 파싱처리하면 된다.

 

Local JSON 파일을 읽어서 처리하는 걸 예제로 보자.

 [
    {
        "firstName": "길동",
        "lastName": "홍",
        "email": "jdhongv@gmail.com",
        "mobile": "010-1234-1111"
    },
    {
        "firstName": "민아",
        "lastName": "김",
        "email": "minakim@gmail.com",
        "mobile": "010-1234-3333"
    },
    {
        "firstName": "진주",
        "lastName": "마",
        "email": "jjmah@gmail.com",
        "mobile": "010-1234-5555"
    },
    {
        "firstName": "서영",
        "lastName": "이",
        "email": "sylee@gmail.com",
        "mobile": "010-1234-7777"
    }
]

 

<?php
// Local JSON 파일 읽어오기
$json_string = file_get_contents('data.json');
$R = json_decode($json_string, true);
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.
// $R : array data 



foreach ($R as $row) {
    print $row['lastName'];
    print $row['firstName'];
    print ' , ';
    print $row['email'];
    print ' , ';
    print $row['mobile'];
    print '<br />';
}
?> 

 

결과

홍길동 , jdhongv@gmail.com , 010-1234-1111
김민아 , minakim@gmail.com , 010-1234-3333
마진주 , jjmah@gmail.com , 010-1234-5555
이서영 , sylee@gmail.com , 010-1234-7777

 

조금 더 복잡한 JSON 파일을 검색한 걸 테스트한다.

{
    "name": "홍길동",
    "alias": "LInk",
    "members": [
        "소원",
        "예린",
        "은하",
        "유주",
        "신비",
        "엄지"
    ],
    "albums": {
        "EP 1집": "Season of Glass",
        "EP 2집": "Flower Bud",
        "EP 3집": "Snowflake",
        "EP 4집": "THE AWAKENING"
    }
}

 

파싱하는 코드를 두가지로 테스트해보면 print_r 에서 결과를 다르게 보여준다.

<?php
// JSON 파일 읽어오기
$json_string = file_get_contents('weather.json');
// 다차원 배열 반복처리
$R = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json_string, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);
// $R : array data
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.

print_r($R);
echo '<br />';

foreach ($R as $key => $val) {
    if(is_array($val)) {
        echo "$key:<br/>";
    } else {
        echo "$key => $val<br/>";
    }
}
?>
<?php
// Local JSON 파일 읽어오기
$json_string = file_get_contents('weather.json');
$R = json_decode($json_string, true); //
// $R : array data
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.

print_r($R); // 배열 요소를 출력해준다.
echo '<br />';
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>PHP JSON parser sample</title>
    </head>

    <body>
        <h3 id="gname">
        <?php
            echo $R['name'];
            if (array_key_exists('alias', $R))
                printf(" (%s)", $R['alias']);
        ?>
        </h3>
        <p>멤버 구성: <span id="members">
            <?php echo implode(', ', $R['members']);?></span>
        </p>
        <h3>앨범 목록</h3>
        <ul id="albums">
        <?php
            foreach ($R['albums'] as $key => $value) {
                printf("<li>%s: %s</li>\n", $key, $value);
            }
            ?>
        </ul>
    </body>
</html>


출처: https://link2me.tistory.com/1408 [소소한 일상 및 업무TIP 다루기]

 

참고 : 배열에 배열 추가


$arrs = array();                  // 전체 배열을 준비하고
array_push($arrs, $arr)); //$arr 배열을 배열에 넣는다 (다차원 배열)

댓글목록

등록된 댓글이 없습니다.

전체 80
게시물 검색
PHP 목록
번호 제목 글쓴이 조회 날짜
80 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 1337 03-29
열람중 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 3446 03-26
78 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 1498 03-26
77 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 1359 03-17
76 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 1907 11-28
75 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 2125 08-11
74 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 1865 08-10
73 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 2448 08-02
72 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 2531 07-20
71 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 1835 07-05
70 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 2126 05-27
69 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 2877 03-30
68 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 2179 03-30
67 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 2118 03-29
66 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 2112 03-27
65 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 2671 03-10
64 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 2757 02-24
63 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 2174 02-22
62 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 3769 12-31
61 no_profile 운영자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 2422 10-30