Home  >  Article  >  Backend Development  >  How to operate php arrays and objects

How to operate php arrays and objects

墨辰丷
墨辰丷Original
2018-06-09 13:58:493013browse

This article mainly introduces the operation methods of PHP arrays and objects. Interested friends can refer to it. I hope it will be helpful to everyone.

The example of this article describes the method of using recursion to achieve conversion between PHP arrays and objects. The specific implementation method is as follows:

This involves some simple mutual conversion issues between objects and arrays, using recursion I wrote two methods as follows:

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;
}
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;
}
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; 
}

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

php implements loading fonts and saving

PHP implements Chinese character verification code

php recursive traversal to achieve infinite classification

The above is the detailed content of How to operate php arrays and objects. For more information, please follow other related articles on the PHP Chinese website!

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