ホームページ  >  記事  >  バックエンド開発  >  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 に変換できますarray :

$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 文字列で渡され、2 番目のパラメータは変換後のオブジェクトが配列であるかどうかを指定するブール値で渡されます。 (true) またはオブジェクト (false)。デフォルトでは json_decode() 関数が JSON 文字列をオブジェクトに変換するためです。

2 番目のパラメータを 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() 関数の 2 番目のパラメーターが 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);

2 番目のパラメータを 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() 関数の 2 番目のパラメーターを 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。