php convert objects and arrays

*文
Release: 2023-03-18 17:26:01
Original
1449 people have browsed it

This article mainly introduces the method of converting PHP objects and arrays to each other, and realizes the mutual conversion function of objects and arrays through two custom functions. I hope to be helpful.

The specific analysis is as follows:

Here are two functions for converting php anonymous objects and arrays to each other. The code is as follows:

function array2object($array) {
  if (is_array($array)) {
    $obj = new StdClass();
    foreach ($array as $key => $val){
      $obj->$key = $val;
    }
  }
  else { $obj = $array; }
  return $obj;
}
function object2array($object) {
  if (is_object($object)) {
    foreach ($object as $key => $value) {
      $array[$key] = $value;
    }
  }
  else {
    $array = $object;
  }
  return $array;
}
Copy after login


Usage Examples are as follows:


$array = array('foo' => 'bar','one' => 'two','three' => 'four');
$obj = array2object($array);
print $obj->one; // output's "two"
$arr = object2array($obj);
print $arr['foo']; // output's bar
Copy after login

Related recommendations:

php object to json Chinese to Unicode problem

Storage and transmission of PHP objects (serialize objects)

PHP object cloning clone Keywords and __clone() method

The above is the detailed content of php convert objects and arrays. 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!