如何将这样的数组转换为对象?
[128] => Array
(
[status] => "Figure A.
Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution."
)
[129] => Array
(
[status] => "The other day at work, I had some spare time"
)
如何将这样的数组转换为对象?
[128] => Array
(
[status] => "Figure A.
Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution."
)
[129] => Array
(
[status] => "The other day at work, I had some spare time"
)
当前回答
根据你需要的位置和访问对象的方式有不同的方法。
例如:只需对它进行类型转换
$object = (object) $yourArray;
然而,最兼容的方法是使用一个实用程序方法(还不是PHP的一部分),它实现了基于指定类型的字符串的标准PHP强制转换(或者忽略它,只是去引用值):
/**
* dereference a value and optionally setting its type
*
* @param mixed $mixed
* @param null $type (optional)
*
* @return mixed $mixed set as $type
*/
function rettype($mixed, $type = NULL) {
$type === NULL || settype($mixed, $type);
return $mixed;
}
您案例中的使用示例(在线演示):
$yourArray = Array('status' => 'Figure A. ...');
echo rettype($yourArray, 'object')->status; // prints "Figure A. ..."
其他回答
function object_to_array($data)
{
if (is_array($data) || is_object($data))
{
$result = array();
foreach ($data as $key => $value)
{
$result[$key] = object_to_array($value);
}
return $result;
}
return $data;
}
function array_to_object($data)
{
if (is_array($data) || is_object($data))
{
$result= new stdClass();
foreach ($data as $key => $value)
{
$result->$key = array_to_object($value);
}
return $result;
}
return $data;
}
使用我创建的这个函数:
function buildObject($class,$data){
$object = new $class;
foreach($data as $key=>$value){
if(property_exists($class,$key)){
$object->{'set'.ucfirst($key)}($value);
}
}
return $object;
}
用法:
$myObject = buildObject('MyClassName',$myArray);
您可以简单地使用类型强制转换将数组转换为对象。
// *convert array to object* Array([id]=> 321313[username]=>shahbaz)
$object = (object) $array_name;
//now it is converted to object and you can access it.
echo $object->username;
简单的方法是
$object = (object)$array;
但这不是你想要的。如果你想要对象,你想要实现一些东西,但这在这个问题中是缺失的。仅仅为了使用对象而使用对象是没有意义的。
你可以使用反射:
<?php
$array = ['name'=>'maria','age'=>33];
class Person {
public $name;
public $age;
public function __construct(string $name, string $age){
$this->name = $name;
$this->age = $age;
}
}
function arrayToObject(array $array, string $class_name){
$r = new ReflectionClass($class_name);
$object = $r->newInstanceWithoutConstructor();
$list = $r->getProperties();
foreach($list as $prop){
$prop->setAccessible(true);
if(isset($array[$prop->name]))
$prop->setValue($object, $array[$prop->name]);
}
return $object;
}
$pessoa1 = arrayToObject($array, 'Person');
var_dump($pessoa1);