28FebFrom the Array to the Object
The other day working late with my colleague Tudor, who also have a blog at blog.motane.lu, we found that in one point of our application we had to use an object but we had an Array. At this point we found two possible solutions, the first rewrite our code to use the Array instead the object or the second and more sophisticated solution convert the Array to an Object.
The tricky point was that the Array could contain more Arrays so we had to write a recursive function to accomplish our objective.
Tudor, at the end, gave the following method to be able to do the conversion.
/**
* Recursively converts an array to a stdClass object
*
* @param array $array
* @return stdClass
*/
protected function _convertToStdObject(array $array){
$obj = new stdClass();
foreach($array as $key => $value) {
if(!is_array($value)) {
$obj->{$key} = $value;
}else{
$obj->{$key} = $this->_convertToStdObject($value);
}
}
return $obj;
}
Maybe, in the next interviews we will do to our PHP Developers candidates, we will ask about this and see how they solve the problem
3 Responses and Counting...
Tudor
February 28th 2010Now that you’ve wrote it on your blog and advertised it as a possible interview question, it will be quite hard to find candidates that won’t know the answer
PS: you should add the final version, with brackets, like $obj->{$key}
Lloyd Moore
One interview question could be how to rewrite the code without using recursion (extra points for co-routines) and the advantages / disadvantages of both solutions.
admin
Nice questions Lloyd! I will write down them for future use…