Skip to content

Instantly share code, notes, and snippets.

@AndreiLN
Created February 22, 2019 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreiLN/3708ab829c26cee4711b1df551d1385f to your computer and use it in GitHub Desktop.
Save AndreiLN/3708ab829c26cee4711b1df551d1385f to your computer and use it in GitHub Desktop.
Converts Doctrine Model to Array
/**
* Converts doctrine to array
* @param $data
* @param $single it's run's only once (no recursion)
* @return array
*/
public function doctrine_to_array($data, $single = false) {
if (is_object($data)) { // its object
$methods = get_class_methods($data);
$methods = array_filter($methods, function($val){ return preg_match('/^get/', $val); });
$return = [];
if(count($methods)){
foreach($methods as $method){
$prop = lcfirst(preg_replace('/^get/', "", $method));
$val = $data->$method();
if(!$single){
$return[$prop] = $this->doctrine_to_array($val, $single);
} else {
if(!is_array($val) && !is_object($val)){
$return[$prop] = $val;
}
}
}
}
return $return;
} else if(is_array($data)){
if(count($data)){
foreach($data as $idx => $val){
$data[$idx] = $this->doctrine_to_array($val, $single);
}
}
}
return $data; // it's not array or object
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment