12

2DJSON文字列の作成について質問がありました

ここで、以下にアクセスできない理由を知りたいと思います。

$json_str = '{"urls":["http://example.com/001.jpg","http://example.com/003.jpg","http://example.com/002.jpg"],"alts":["testing int chars àèéìòóù stop","second description",""],"favs":["true", "false", "false"]}';

$j_string_decoded = json_decode($json_str);
// echo print_r($j_string_decoded); // OK

// test get url from second item
echo j_string_decoded['urls'][1];
// Fatal error: Cannot use object of type stdClass as array
4

3 に答える 3

27

配列のような構文でアクセスしています。

echo j_string_decoded['urls'][1];

一方、オブジェクトが返されます。

true2番目の引数を:に指定して、配列に変換します。

$j_string_decoded = json_decode($json_str, true);

それを作る:

$json_str = '{"urls":["http://site.com/001.jpg","http://site.com/003.jpg","http://site.com/002.jpg"],"alts":["testing int chars àèéìòóù stop","second description",""],"favs":["true", "false", "false"]}';

$j_string_decoded = json_decode($json_str, true);
echo j_string_decoded['urls'][1];

またはこれを試してください:

$j_string_decoded->urls[1]

->オブジェクトに使用される演算子に注意してください。

ドキュメントからの引用:

適切なPHPタイプでjsonにエンコードされた値を返します。true、false、およびnull(大文字と小文字を区別しない)の値は、それぞれTRUE、FALSE、およびNULLとして返されます。jsonをデコードできない場合、またはエンコードされたデータが再帰制限よりも深い場合は、NULLが返されます。

http://php.net/manual/en/function.json-decode.php

于 2010-11-02T18:16:01.583 に答える
7

json_decodeデフォルトでは、JSON辞書はPHPオブジェクトに変換されるため、次のように値にアクセスします。$j_string_decoded->urls[1]

json_decode($json_str,true)または、連想配列を返すように追加の引数を渡すこともできます。これにより、$j_string_decoded['urls'][1]

于 2010-11-02T18:16:46.027 に答える
6

使用する:

json_decode($jsonstring, true);

配列を返します。

于 2010-11-02T18:15:09.460 に答える