在PHP中,数组和对象之间可以相互转换。以下是一些常用的方法:
$object = new stdClass();
$object->name = 'John';
$object->age = 30;
$array = (array) $object;
print_r($array);
json_decode
函数将数组转换为对象。$array = array('name' => 'John', 'age' => 30);
$object = (object) $array;
var_dump($object);
// 或者使用json_decode
$json = json_encode($array);
$object = json_decode($json);
var_dump($object);
get_object_vars
函数获取对象的属性并将其转换为数组。$object = new stdClass();
$object->name = 'John';
$object->age = 30;
$array = get_object_vars($object);
print_r($array);
json_encode
和json_decode
函数进行对象和数组之间的转换。$object = new stdClass();
$object->name = 'John';
$object->age = 30;
// 将对象转换为数组
$array = json_decode(json_encode($object), true);
print_r($array);
// 将数组转换为对象
$object = json_decode(json_encode($array));
var_dump($object);