Home > php教程 > php手册 > body text

PHP数组与对象之间使用递归实现转换的方法,数组递归

WBOY
Release: 2016-06-13 09:00:06
Original
993 people have browsed it

PHP数组与对象之间使用递归实现转换的方法,数组递归

本文实例讲述了PHP数组与对象之间使用递归实现转换的方法。分享给大家供大家参考。具体实现方法如下:

这里涉及一些简单的对象与数组的相互转换的问题,采用递归写了两个方法如下:

function arrayToObject($e){  
   if( gettype($e)!='array' ) return;
   foreach($e as $k=>$v){
     if( gettype($v)=='array' || getType($v)=='object' )
        $e[$k]=(object)arrayToObject($v);
   }
    return (object)$e;
}

Copy after login
function objectToArray($e){
  $e=(array)$e;
  foreach($e as $k=>$v){
    if( gettype($v)=='resource' ) return;
    if( gettype($v)=='object' || gettype($v)=='array' )
      $e[$k]=(array)objectToArray($v);
  }
  return $e;
}

Copy after login
function object_to_array($e) { 
  $_arr = is_object($e) ? get_object_vars($e) : $e; 
  foreach ($_arr as $key => $val) { 
    $val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val; 
    $arr[$key] = $val; 
  } 
  return $arr; 
}

Copy after login

希望本文所述对大家的php程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template