Recently, I am using ThinkPHP to develop an application for JD.com service market. However, the data returned by JD.com service market interface is Array of objects. However, you need to take out the attributes one by one and put them into the array and then use ThinkPHP's addAll or add method to write them to the database. However, there are dozens of fields returned each time, and each time the splicing is done, it will collapse. Sure enough, it's still the same sentence, when you feel that you can't stand it, you will find a way to change it. So I thought about it, if there was a function that could automatically convert an object array into a normal array. So the universal internet search is back. Baidu made a pass. . . Sure enough, some seniors have already dealt with it, so I will record it here.
Copy code The code is as follows:
/**
* [std_class_object_to_array Convert object to array]
* @param [stdclass] $stdclassobject [object]
* @return [array] [array]
*/
function std_class_object_to_array($stdclassobject)
{
$_array = is_object($stdclassobject) ? get_object_vars($stdclassobject) : $stdclassobject;
foreach ($_array as $key => $value) {
$value = (is_array($value) || is_object($value)) ? std_class_object_to_array($value) : $value;
$array[$key] = $value;
}
return $array;
}
In this way, the object array is elegantly converted into an ordinary array. Using my brain, the code size was reduced and the functions were implemented elegantly. Kill two birds with one stone, why not?