How to convert object to array in php

藏色散人
Release: 2023-03-07 18:50:01
Original
3398 people have browsed it

How to convert an object to an array in php: How to convert an object to an array in php: First create a PHP sample file; then access the object in the form of an array through the "get_object_vars (object $obj)" function. Can.

How to convert object to array in php

The operating environment of this tutorial: Windows 7 system, PHP version 5.6. This method is suitable for all brands of computers.

Recommended: "PHP Video Tutorial"

php object to array function

Regarding the object in PHP that you want to access in the form of an array, 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)  // Point2D换成__construct
  {
    $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

Object to array specific implementation:

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

array_map()The function converts the user's Define a function to act on each value in the array and return an array with new values ​​after the user-defined function is applied.

Specific implementation of converting array to object:

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

This method is applicable to all brands of computers.

The above is the detailed content of How to convert object to array in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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