Created
August 23, 2012 07:52
-
-
Save mgng/3433992 to your computer and use it in GitHub Desktop.
array と stdClass
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $data = array( | |
| "id" => "mgng", | |
| "name" => "ムグ" | |
| ); | |
| echo $data['name']; | |
| $data = new stdClass(); | |
| $data->id = "mgng"; | |
| $data->name = "ムグ"; | |
| echo $data->name; | |
| // stdClass で初期値を設定するには、なんか変だけど、 | |
| // json_decode + JSON とか、array → object キャスト すれば可能。 | |
| $data = json_decode('{ | |
| "id" : "mgng", | |
| "name" : "ムグ" | |
| }'); | |
| echo $data->name; | |
| $data = (object)array( | |
| "id" => "mgng", | |
| "name" => "ムグ" | |
| ); | |
| echo $data->name; | |
| // キーを変数にする場合、配列だと[]だけど | |
| $data = array( | |
| "id" => "mgng", | |
| "name" => "ムグ" | |
| ); | |
| $key = 'name'; | |
| echo $data[$key]; | |
| // stdClass の場合は{}を使う。 | |
| $data = json_decode('{ | |
| "id" : "mgng", | |
| "name" : "ムグ" | |
| }'); | |
| $key = 'name'; | |
| echo $data->{$key}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment