>  기사  >  백엔드 개발  >  JSON 데이터를 PHP 배열이나 객체로 변환하는 방법에 대해 이야기해 보겠습니다.

JSON 데이터를 PHP 배열이나 객체로 변환하는 방법에 대해 이야기해 보겠습니다.

PHPz
PHPz원래의
2023-04-17 15:25:58574검색

JSON 형식은 단순성, 사용 용이성, 속도 및 효율성이라는 장점으로 인해 경량 데이터 교환 형식으로 널리 사용되는 데이터 형식이 되었습니다. PHP에서는 json_decode() 함수를 사용하여 JSON 문자열을 PHP 배열 또는 객체로 변환할 수 있습니다. 이 기사에서는 JSON 형식의 데이터를 PHP 배열 또는 개체로 변환하는 방법을 소개하고 JSON에서 배열 및 개체를 처리하는 방법도 살펴봅니다.

1. JSON 문자열을 PHP 배열로 변환

다음은 JSON 데이터의 예입니다.

{
   "name": "Tom",
   "age": 26,
   "email": "tom@example.com",
   "hobbies": ["reading", "swimming", "traveling"],
   "address": {
      "city": "Beijing",
      "province": "Beijing",
      "country": "China"
   }
}

json_decode() 함수를 사용하여 PHP 배열로 변환할 수 있습니다.

$json = '{
   "name": "Tom",
   "age": 26,
   "email": "tom@example.com",
   "hobbies": ["reading", "swimming", "traveling"],
   "address": {
      "city": "Beijing",
      "province": "Beijing",
      "country": "China"
   }
}';

$array = json_decode($json, true);

json_decode() 함수를 호출할 때 , 첫 번째 매개변수는 변환할 JSON 문자열로 전달되고, 두 번째 매개변수는 변환된 객체가 배열(true)인지 객체(false)인지 지정하기 위해 부울 값으로 전달됩니다. 왜냐하면 기본적으로 json_decode() 함수는 JSON 문자열을 객체로 변환합니다.

두 번째 매개변수를 true로 설정하면 반환 값은 PHP 배열이고 결과는 다음과 같습니다.

Array
(
    [name] => Tom
    [age] => 26
    [email] => tom@example.com
    [hobbies] => Array
        (
            [0] => reading
            [1] => swimming
            [2] => traveling
        )

    [address] => Array
        (
            [city] => Beijing
            [province] => Beijing
            [country] => China
        )

)

2. JSON 문자열을 PHP 객체로 변환

json_decode()의 두 번째 매개변수가 function is false로 설정되면 PHP 객체가 반환됩니다. 다음은 샘플 코드입니다.

$json = '{
   "name": "Tom",
   "age": 26,
   "email": "tom@example.com",
   "hobbies": ["reading", "swimming", "traveling"],
   "address": {
      "city": "Beijing",
      "province": "Beijing",
      "country": "China"
   }
}';

$obj = json_decode($json, false);

두 번째 매개 변수를 false로 설정하면 $obj는 PHP 객체이며 결과는 다음과 같습니다.

stdClass Object
(
    [name] => Tom
    [age] => 26
    [email] => tom@example.com
    [hobbies] => Array
        (
            [0] => reading
            [1] => swimming
            [2] => traveling
        )

    [address] => stdClass Object
        (
            [city] => Beijing
            [province] => Beijing
            [country] => China
        )

)

3. JSON에서 배열 처리

JSON 데이터에 배열이 포함된 경우 json_decode() 함수를 사용하여 PHP 배열이나 객체로 변환할 수 있습니다. 다음은 배열을 포함하는 JSON 데이터의 예입니다.

{
   "name": "Tom",
   "age": 26,
   "email": "tom@example.com",
   "hobbies": ["reading", "swimming", "traveling"],
   "scores": [
      {"subject": "math", "score": 90},
      {"subject": "physics", "score": 85},
      {"subject": "chemistry", "score": 78}
   ]
}

json_decode() 함수를 사용하여 이를 PHP 배열로 변환할 수 있습니다.

$json = '{
   "name": "Tom",
   "age": 26,
   "email": "tom@example.com",
   "hobbies": ["reading", "swimming", "traveling"],
   "scores": [
      {"subject": "math", "score": 90},
      {"subject": "physics", "score": 85},
      {"subject": "chemistry", "score": 78}
   ]
}';

$array = json_decode($json, true);

변환된 결과는 다음과 같습니다.

Array
(
    [name] => Tom
    [age] => 26
    [email] => tom@example.com
    [hobbies] => Array
        (
            [0] => reading
            [1] => swimming
            [2] => traveling
        )

    [scores] => Array
        (
            [0] => Array
                (
                    [subject] => math
                    [score] => 90
                )

            [1] => Array
                (
                    [subject] => physics
                    [score] => 85
                )

            [2] => Array
                (
                    [subject] => chemistry
                    [score] => 78
                )

        )

)

첫 번째 부분도 변환할 수 있습니다. json_decode() 함수의 두 매개변수를 false로 설정하여 PHP 객체로 변환합니다. 변환된 결과는 다음과 같습니다.

stdClass Object
(
    [name] => Tom
    [age] => 26
    [email] => tom@example.com
    [hobbies] => Array
        (
            [0] => reading
            [1] => swimming
            [2] => traveling
        )

    [scores] => Array
        (
            [0] => stdClass Object
                (
                    [subject] => math
                    [score] => 90
                )

            [1] => stdClass Object
                (
                    [subject] => physics
                    [score] => 85
                )

            [2] => stdClass Object
                (
                    [subject] => chemistry
                    [score] => 78
                )

        )

)

4. JSON에서 객체 처리

JSON 데이터에 객체가 포함되어 있는 경우 json_decode() 함수를 사용하여 이를 PHP 배열이나 객체로 변환할 수도 있습니다. 다음은 개체가 포함된 JSON 데이터의 예입니다.

{
   "name": "Tom",
   "age": 26,
   "email": "tom@example.com",
   "hobbies": ["reading", "swimming", "traveling"],
   "address": {
      "city": "Beijing",
      "province": "Beijing",
      "country": "China"
   },
   "scores": {
      "math": 90,
      "physics": 85,
      "chemistry": 78
   }
}

json_decode() 함수를 사용하여 이를 PHP 배열 또는 개체로 변환할 수 있습니다.

$json = '{
   "name": "Tom",
   "age": 26,
   "email": "tom@example.com",
   "hobbies": ["reading", "swimming", "traveling"],
   "address": {
      "city": "Beijing",
      "province": "Beijing",
      "country": "China"
   },
   "scores": {
      "math": 90,
      "physics": 85,
      "chemistry": 78
   }
}';

$array = json_decode($json, true);
$obj = json_decode($json, false);

변환된 PHP 배열 및 개체는 다음과 같습니다.

Array
(
    [name] => Tom
    [age] => 26
    [email] => tom@example.com
    [hobbies] => Array
        (
            [0] => reading
            [1] => swimming
            [2] => traveling
        )

    [address] => Array
        (
            [city] => Beijing
            [province] => Beijing
            [country] => China
        )

    [scores] => Array
        (
            [math] => 90
            [physics] => 85
            [chemistry] => 78
        )

)

stdClass Object
(
    [name] => Tom
    [age] => 26
    [email] => tom@example.com
    [hobbies] => Array
        (
            [0] => reading
            [1] => swimming
            [2] => traveling
        )

    [address] => stdClass Object
        (
            [city] => Beijing
            [province] => Beijing
            [country] => China
        )

    [scores] => stdClass Object
        (
            [math] => 90
            [physics] => 85
            [chemistry] => 78
        )

)

5 . 변환 PHP 배열 또는 개체를 JSON으로 변환

JSON 데이터의 구문 분석 및 조작을 완료한 후 후속 처리 또는 전송을 위해 PHP 배열 또는 개체를 JSON 형식 문자열로 변환해야 할 수도 있습니다. json_encode() 함수를 사용하여 PHP 배열 또는 객체를 JSON 형식 문자열로 변환할 수 있습니다. 다음은 샘플 코드입니다.

$array = array(
   'name' => 'Tom',
   'age' => 26,
   'email' => 'tom@example.com',
   'hobbies' => array('reading', 'swimming', 'traveling'),
   'address' => array(
      'city' => 'Beijing',
      'province' => 'Beijing',
      'country' => 'China'
   ),
   'scores' => array(
      'math' => 90,
      'physics' => 85,
      'chemistry' => 78
   )
);

$json = json_encode($array);

json_encode() 함수를 호출한 후 $json의 값은 변환된 JSON 형식 문자열이며 결과는 다음과 같습니다.

{
   "name":"Tom",
   "age":26,
   "email":"tom@example.com",
   "hobbies":["reading","swimming","traveling"],
   "address":{
      "city":"Beijing",
      "province":"Beijing",
      "country":"China"
   },
   "scores":{
      "math":90,
      "physics":85,
      "chemistry":78
   }
}

6. PHP 배열 또는 객체를 JSON으로 변환합니다.

PHP에서 JSON 형식의 데이터를 직접 출력해야 하는 경우 json_encode() 함수를 호출한 후 결과를 직접 출력할 수 있습니다. 다음 예:

$array = array(
   'name' => 'Tom',
   'age' => 26,
   'email' => 'tom@example.com',
   'hobbies' => array('reading', 'swimming', 'traveling'),
   'address' => array(
      'city' => 'Beijing',
      'province' => 'Beijing',
      'country' => 'China'
   ),
   'scores' => array(
      'math' => 90,
      'physics' => 85,
      'chemistry' => 78
   )
);

header('Content-Type: application/json');
echo json_encode($array);

위 예에서는 header() 함수를 통해 응답 헤더 정보를 설정하고 ContentType을 application/json으로 설정하여 반환되는 데이터가 JSON 형식임을 나타냅니다. 그런 다음 echo를 사용하여 변환된 JSON 데이터를 출력합니다.

결론

이 글에서는 주로 JSON 데이터를 PHP 배열이나 개체로 변환하는 방법을 소개하고, JSON에서 배열과 개체를 처리하는 방법을 살펴보고, PHP 배열이나 개체를 JSON 형식 문자열로 변환하는 방법을 보여줍니다. 이 글이 PHP 개발자들에게 도움이 되기를 바랍니다.

위 내용은 JSON 데이터를 PHP 배열이나 객체로 변환하는 방법에 대해 이야기해 보겠습니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.