如何将这样的数组转换为对象?
[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"
)
当前回答
递归是你的朋友:
function __toObject(Array $arr) {
$obj = new stdClass();
foreach($arr as $key=>$val) {
if (is_array($val)) {
$val = __toObject($val);
}
$obj->$key = $val;
}
return $obj;
}
其他回答
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;
}
快速攻击:
// assuming $var is a multidimensional array
$obj = json_decode (json_encode ($var), FALSE);
不漂亮,但很好用。
我用了很简单的方法,
$list_years = array();
$object = new stdClass();
$object->year_id = 1 ;
$object->year_name = 2001 ;
$list_years[] = $object;
多维数组转换为对象。此代码用于转换必应搜索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);
}
您可以简单地使用类型强制转换将数组转换为对象。
// *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;