Home > Backend Development > PHP Tutorial > PHP object to array function

PHP object to array function

王林
Release: 2023-04-07 11:18:01
Original
6083 people have browsed it

PHP object to array function

If you want to access objects in the form of arrays in PHP, you need to use the get_object_vars() function. Let’s first introduce this function.

The official documentation explains this:

array get_object_vars ( object $obj )
Copy after login

Returns an associative array composed of attributes defined in the object specified by obj.

Example:

<?php
class Point2D {
  var $x, $y;
  var $label;
  function Point2D($x, $y)
  {
    $this->x = $x;
    $this->y = $y;
  }
  function setLabel($label)
  {
    $this->label = $label;
  }
  function getPoint()
  {
    return array("x" => $this->x,
           "y" => $this->y,
           "label" => $this->label);
  }
}
// "$label" is declared but not defined
$p1 = new Point2D(1.233, 3.445);
print_r(get_object_vars($p1));
$p1->setLabel("point #1");
print_r(get_object_vars($p1));
?>
Copy after login

Output:

Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] =>
 )
 Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] => point #1
 )
Copy after login

Specific implementation of converting object to array:

function objectToArray($obj) {
  //首先判断是否是对象
  $arr = is_object($obj) ? get_object_vars($obj) : $obj;
  if(is_array($arr)) {
    //这里相当于递归了一下,如果子元素还是对象的话继续向下转换
    return array_map(__FUNCTION__, $arr);
  }else {
    return $arr;
  }
}
Copy after login

The specific implementation of converting arrays to objects:

function arrayToObject($arr) {
  if(is_array($arr)) {
    return (object)array_map(__FUNCTION__, $arr);
  }else {
    return $arr;
  }
}
Copy after login

For more related content, please visit the PHP Chinese website: PHP Video Tutorial

The above is the detailed content of PHP object to array function. 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