>  기사  >  백엔드 개발  >  PHP에서 JSON을 배열이나 개체로 구문 분석하는 방법

PHP에서 JSON을 배열이나 개체로 구문 분석하는 방법

Linda Hamilton
Linda Hamilton원래의
2024-10-21 14:47:30888검색

How to Parse JSON as an Array or Object in PHP

PHP로 JSON 구문 분석

JSON은 웹 애플리케이션과 API 간에 데이터를 교환하는 데 자주 사용되는 널리 사용되는 데이터 형식입니다. PHP에서는 json_decode() 함수를 사용하여 JSON 문자열을 PHP 배열 또는 개체로 구문 분석할 수 있습니다.

JSON을 개체로 구문 분석하려면 $json = json_decode($data) 구문을 사용하면 됩니다. 그런 다음 점 표기법을 사용하여 결과 객체에 액세스할 수 있습니다.

그러나 JSON을 배열로 구문 분석하려면 json_decode() 함수에 true라는 두 번째 인수를 전달해야 합니다. 그러면 키가 속성 이름이고 값이 해당 값인 연관 배열이 반환됩니다.

다음 JSON 데이터를 예로 들어 보겠습니다.

{
    "kind": "shopping#products",
    "etag": "\"T9uPnY2MZMB71TDpKXXZdr3yWX4/qtJ5vmpftFWNfijyLD9ti2Xpj-w\"",
    "id": "tag:google.com,2010:shopping/products",
    "selfLink": "https://www.googleapis.com/shopping/search/v1/public/products?country\u003dus&q\u003dsony&maxResults\u003d3&startIndex\u003d2",
    "nextLink": "https://www.googleapis.com/shopping/search/v1/public/products?country\u003dus&q\u003dsony&maxResults\u003d3&startIndex\u003d5",
    "previousLink": "https://www.googleapis.com/shopping/search/v1/public/products?country\u003dus&q\u003dsony&maxResults\u003d3&startIndex\u003d1",
    "totalItems": 633694,
    "startIndex": 2,
    "itemsPerPage": 3,
    "currentItemCount": 3,
    "items": [
        {
            "kind": "shopping#product",
            "id": "tag:google.com,2010:shopping/products/1161353/11882813508247586172",
            "selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/1161353/gid/11882813508247586172",
            "product": {
                "googleId": "11882813508247586172",
                "author": {
                    "name": "Buy.com",
                    "accountId": "1161353"
                },
                "creationTime": "2011-04-24T05:13:38.000Z",
                "modificationTime": "2011-08-05T17:45:24.000Z",
                "country": "US",
                "language": "en",
                "title": "Sony BRAVIA KDL-46EX720 46 inch 3D LED HDTV 1080p 120Hz",
                "description": "Entertainment lovers the slim Sony EX720-Series LED HDTV is for you. See precise motion detail plus watch your favorite 2D or 3D entertainment in clear, vivid Full HD 1080p picture quality with incredible contrast. You can even connect to the internet and access a great selection of online entertainment with Netflix , Hulu Plus , Pandora , Qriocity and more - there s always something on. Plus video chat with friends and family when you Skype on the big screen.",
                "link": "http://clickfrom.buy.com/default.asp?adid\u003d17902&sURL\u003dhttp%3A%2F%2Fwww.buy.com%2Fprod%2Fsony-bravia-kdl-46ex720-46-3d-led-hdtv-1080p-120hz%2Fq%2Fsellerid%2F10004001%2Floc%2F111%2F219891693.html",
                "brand": "Sony",
                "condition": "new",
                "gtin": "00027242817081",
                "gtins": [
                    "00027242817081"
                ],
                "inventories": [
                    {
                        "channel": "online",
                        "availability": "inStock",
                        "price": 1348.0,
                        "currency": "USD"
                    }
                ],
                "images": [
                    {
                        "link": "http://ak.buy.com/PI/0/1000/219891693.jpg"
                    }
                ]
            }
        }
    ]
}

이 JSON을 다음과 같이 구문 분석합니다. 배열인 경우 다음 구문을 사용하세요.

<code class="php">$json = json_decode($data, true);</code>

이렇게 하면 다음 배열이 반환됩니다.

[
    "kind" => "shopping#products",
    "etag" => "\"T9uPnY2MZMB71TDpKXXZdr3yWX4/qtJ5vmpftFWNfijyLD9ti2Xpj-w\"",
    "id" => "tag:google.com,2010:shopping/products",
    "selfLink" => "https://www.googleapis.com/shopping/search/v1/public/products?country\u003dus&amp;q\u003dsony&amp;maxResults\u003d3&amp;startIndex\u003d2",
    "nextLink" => "https://www.googleapis.com/shopping/search/v1/public/products?country\u003dus&amp;q\u003dsony&amp;maxResults\u003d3&amp;startIndex\u003d5",
    "previousLink" => "https://www.googleapis.com/shopping/search/v1/public/products?country\u003dus&amp;q\u003dsony&amp;maxResults\u003d3&amp;startIndex\u003d1",
    "totalItems" => 633694,
    "startIndex" => 2,
    "itemsPerPage" => 3,
    "currentItemCount" => 3,
    "items" => [
        [
            "kind" => "shopping#product",
            "id" => "tag:google.com,2010:shopping/products/1161353/11882813508247586172",
            "selfLink" => "https://www.googleapis.com/shopping/search/v1/public/products/1161353/gid/11882813508247586172",
            "product" => [
                "googleId" => "11882813508247586172",
                "author" => [
                    "name" => "Buy.com",
                    "accountId" => "1161353"
                ],
                "creationTime" => "2011-04-24T05:13:38.000Z",
                "modificationTime" => "2011-08-05T17:45:24.000Z",
                "country" => "US",
                "language" => "en",
                "title" => "Sony BRAVIA KDL-46EX720 46 inch 3D LED HDTV 1080p 120Hz",
                "description" => "Entertainment lovers the slim Sony EX720-Series LED HDTV is for you. See precise motion detail plus watch your favorite 2D or 3D entertainment in clear, vivid Full HD 1080p picture quality with incredible contrast. You can even connect to the internet and access a great selection of online entertainment with Netflix , Hulu Plus , Pandora , Qriocity and more - there s always something on. Plus video chat with friends and family when you Skype on the big screen.",

위 내용은 PHP에서 JSON을 배열이나 개체로 구문 분석하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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