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

PHP object to array function

王林
王林Original
2019-08-31 17:46:365989browse

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 )

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));
?>

Output:

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

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

The specific implementation of converting arrays to objects:

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

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!

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