Is there a way to assign an object property to an array?
Pretty sure there is a way to do this but what I tried so far does not work
Consider we have an object $localDB with some properties, I was looking for a clean way to build the $connexionInfo array without casting $localDB or using a foreach loop.
// This would be too easy if it worked
$connexionInfo = array( "UID" => $localDB->uid,
"PWD" => $localDB->pwd,
"Database" => $localDB->DB
);
// tried using {} a few different ways, also does not seem to work
$connexionInfo = array( "UID" => {$localDB->uid},
"PWD" => {$localDB->pwd},
"Database"=> {$localDB->DB}
);
I'm pretty sure there is a clean way to do this. Anyone?
UPdate:
// 开发者_运维技巧Contrary to what I posted above ... this DOES actually do what it's supposed to! $connectionInfo = array("UID" => $localDB->uid, "PWD" =>$localDB->pwd, "Database"=> $localDB->DB);
use this function
function objectToArray($object)
{
$array=array();
foreach($object as $member=>$data)
{
$array[$member]=$data;
}
return $array;
}
You can try type casting your PHP 5 object to an array.
$array = (array) $localDB;
without casting or foreach then see the manual
get_object_vars
depending on the levels within the object you can just do
$array = (array) $object;
If you want arrays within the array you will have to use some kind of recursion
(I think, this was all I needed so I didn't test any further for my case)
But it looks like this would be a cleaner version of what you want
As stated in a comment under initial question, this is how one can assign obj properties to an array value:
$connectionInfo = array("UID" => $localDB->uid, "PWD" =>$localDB->pwd, "Database"=> $localDB->DB);
精彩评论