Skip to content

Instantly share code, notes, and snippets.

@mgng
Created August 23, 2012 07:52
Show Gist options
  • Select an option

  • Save mgng/3433992 to your computer and use it in GitHub Desktop.

Select an option

Save mgng/3433992 to your computer and use it in GitHub Desktop.
array と stdClass
<?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