How to operate php arrays and objects

墨辰丷
Release: 2023-03-31 09:14:02
Original
3012 people have browsed it

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

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!

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!