如何将这样的数组转换为对象?
[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"
)
当前回答
多维数组转换为对象。此代码用于转换必应搜索API的尝试和捕获方法。
try {
// Perform the Web request and get the JSON response
$context = stream_context_create($options);
$results = file_get_contents($url . "?cc=" . $country . "&category=" . $type, false, $context);
$results = json_decode($results);
return response()->json($results);
} catch (\Exception $e) {
$results = array('value' => array(
(object) array(
"name" => "Unable to Retrive News",
"url" => "http://www.sample.com/",
"image" => (object) array("thumbnail" => (object) array("contentUrl" => "")),
"publishedAt" => "",
"description" => "")
)
);
$results = (object) $results;
return response()->json($results);
}
其他回答
受到所有这些代码的启发,我尝试创建一个增强版本,支持:特定的类名,避免构造函数方法,'beans'模式和严格模式(仅设置现有属性):
class Util {
static function arrayToObject($array, $class = 'stdClass', $strict = false) {
if (!is_array($array)) {
return $array;
}
//create an instance of an class without calling class's constructor
$object = unserialize(
sprintf(
'O:%d:"%s":0:{}', strlen($class), $class
)
);
if (is_array($array) && count($array) > 0) {
foreach ($array as $name => $value) {
$name = strtolower(trim($name));
if (!empty($name)) {
if(method_exists($object, 'set'.$name)){
$object->{'set'.$name}(Util::arrayToObject($value));
}else{
if(($strict)){
if(property_exists($class, $name)){
$object->$name = Util::arrayToObject($value);
}
}else{
$object->$name = Util::arrayToObject($value);
}
}
}
}
return $object;
} else {
return FALSE;
}
}
}
这需要PHP7,因为我选择使用lambda函数来锁定主函数中的'innerfunc'。lambda函数是递归调用的,因此需要:"use (&$innerfunc)"。你可以在PHP5中这样做,但不能隐藏innerfunc。
function convertArray2Object($defs) {
$innerfunc = function ($a) use ( &$innerfunc ) {
return (is_array($a)) ? (object) array_map($innerfunc, $a) : $a;
};
return (object) array_map($innerfunc, $defs);
}
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;
}
容易:
$object = json_decode(json_encode($array));
例子:
$array = array(
'key' => array(
'k' => 'value',
),
'group' => array('a', 'b', 'c')
);
$object = json_decode(json_encode($array));
那么,以下是正确的:
$object->key->k === 'value';
$object->group === array('a', 'b', 'c')
根据你需要的位置和访问对象的方式有不同的方法。
例如:只需对它进行类型转换
$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. ..."