如何将这样的数组转换为对象?
[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);
}
其他回答
使用我创建的这个函数:
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;
世界上最好的方法:)
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;
}
}
如果使用不同的方法,就会出现问题。这是最好的方法。你所见过的。
有点复杂,但很容易扩展的技术:
假设你有一个数组
$a = [
'name' => 'ankit',
'age' => '33',
'dob' => '1984-04-12'
];
假设您有一个Person类,它可能有来自这个数组的或多或少的属性。例如
class Person
{
private $name;
private $dob;
private $age;
private $company;
private $city;
}
如果你还想把数组改成person对象。你可以使用ArrayIterator类。
$arrayIterator = new \ArrayIterator($a); // Pass your array in the argument.
现在你有了迭代器对象。
创建一个扩展FilterIterator class的类;你必须定义抽象方法accept。遵循示例
class PersonIterator extends \FilterIterator
{
public function accept()
{
return property_exists('Person', parent::current());
}
}
上面的实现只在类中存在该属性时才会绑定它。
在类PersonIterator中再添加一个方法
public function getObject(Person $object)
{
foreach ($this as $key => $value)
{
$object->{'set' . underscoreToCamelCase($key)}($value);
}
return $object;
}
确保在类中定义了mutator。 现在,您可以在想要创建对象的地方调用这些函数。
$arrayiterator = new \ArrayIterator($a);
$personIterator = new \PersonIterator($arrayiterator);
$personIterator->getObject(); // this will return your Person Object.
它的方法很简单,这将为递归数组创建一个对象:
$object = json_decode(json_encode((object) $yourArray), FALSE);