Home  >  Article  >  Backend Development  >  PHP中把对象数组转换成普通数组的方法_PHP

PHP中把对象数组转换成普通数组的方法_PHP

WBOY
WBOYOriginal
2016-05-30 08:46:461010browse

最近在用ThinkPHP开发一个京东服务市场的应用,然而京东服务市场接口返回的数据是个对象数组。然而需要一个个属性取出来放到数组里面然后再利用ThinkPHP的addAll或者add方法写入数据库。然而每次返回的字段有几十个,每次这么拼接都要崩溃了。果然还是那句话,当你感到无法忍受的时候你就会想办法改变。于是想了下,如果有个函数传个对象数组进去可以自动转成普通数组就好了。因而万能的互联网搜索又来了。百度了一通。。。果然有前辈已经处理过了,在此记录一下。

代码如下:


/**
* [std_class_object_to_array 将对象转成数组]
* @param [stdclass] $stdclassobject [对象]
* @return [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;
}


就这样,对象数组就优雅地转成了普通的数组。动动脑子,代码量下来了,功能也优雅地就实现了。一举两得,何乐而不为呢?
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn