如何将这样的数组转换为对象?
[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"
)
当前回答
CakePHP有一个递归的Set::map类,基本上是将数组映射到对象。为了使对象看起来像你想要的样子,你可能需要改变数组的样子。
http://api.cakephp.org/view_source/set/#line-158
最坏的情况下,您可能会从这个函数中得到一些想法。
其他回答
快速攻击:
// assuming $var is a multidimensional array
$obj = json_decode (json_encode ($var), FALSE);
不漂亮,但很好用。
递归是你的朋友:
function __toObject(Array $arr) {
$obj = new stdClass();
foreach($arr as $key=>$val) {
if (is_array($val)) {
$val = __toObject($val);
}
$obj->$key = $val;
}
return $obj;
}
多维数组转换为对象。此代码用于转换必应搜索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);
}
实际上,如果你想在多维数组中使用这个你就需要使用一些递归。
static public function array_to_object(array $array)
{
foreach($array as $key => $value)
{
if(is_array($value))
{
$array[$key] = self::array_to_object($value);
}
}
return (object)$array;
}
一个衬套
$object= json_decode(json_encode($result_array, JSON_FORCE_OBJECT));