PHP Implementation of Array and Object Interconversion Operation Example

  • 2021-12-04 09:38:22
  • OfStack

In this paper, an example is given to describe the conversion operation between arrays and objects realized by PHP. Share it for your reference, as follows:

In php, the get_object_vars () function is needed to allow objects to be accessed as arrays. Let's introduce this function first.

The official document explains this:


array get_object_vars ( object $obj )

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

Take a chestnut:


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

Will output:

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

In this way, it is easy to understand that this function is the key function of turning objects into arrays.

Object to Array Concrete Implementation


function objectToArray($obj) {
  // First, judge whether it is an object or not 
  $arr = is_object($obj) ? get_object_vars($obj) : $obj;
  if(is_array($arr)) {
    // This is equivalent to recursion 1 If the child element is still an object, continue to convert down 
    return array_map(__FUNCTION__, $arr);
  }else {
    return $arr;
  }
}

Concrete Implementation of Transforming Array to Object


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

For more readers interested in PHP related content, please check the topics on this site: "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary", "php Common Functions and Skills Summary", "PHP Error and Exception Handling Methods Summary", "PHP Basic Syntax Introduction Course", "php Object-Oriented Programming Introduction Course", "php+mysql Database Operation Introduction Course" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: