如何将这样的数组转换为对象?
[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)函数将数组转换为对象。
$arr= [128=> ['status'=>
'Figure A. Facebook \'s horizontal scrollbars showing up on a 1024x768 screen resolution.'],
129=>['status'=>'The other day at work, I had some spare time']];
$ArrToObject=(object)$arr;
var_dump($ArrToObject);
结果将是一个包含数组的对象:
对象(stdClass)#1048(2){[128]=>数组(1){ ["地位"]= > 字符串(87)“图a: Facebook的水平滚动条显示在1024x768分辨率的屏幕上。”} [129]=>数组(1){ ["地位"]= > 字符串(44)“前几天上班,我有一些空闲时间”}}
其他回答
多维数组转换为对象。此代码用于转换必应搜索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);
}
世界上最好的方法:)
function arrayToObject($conArray)
{
if(is_array($conArray)){
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return (object) array_map(__FUNCTION__, $conArray);
}else{
// Return object
return $conArray;
}
}
如果使用不同的方法,就会出现问题。这是最好的方法。你所见过的。
容易:
$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')
这里有三种方法:
Fake a real object: class convert { public $varible; public function __construct($array) { $this = $array; } public static function toObject($array) { $array = new convert($array); return $array; } } Convert the array into an object by casting it to an object: $array = array( // ... ); $object = (object) $array; Manually convert the array into an object: $object = object; foreach ($arr as $key => $value) { $object->{$key} = $value; }
CakePHP有一个递归的Set::map类,基本上是将数组映射到对象。为了使对象看起来像你想要的样子,你可能需要改变数组的样子。
http://api.cakephp.org/view_source/set/#line-158
最坏的情况下,您可能会从这个函数中得到一些想法。