Examples of transformations of PHP objects (object) and Arrays (array)

Source: Internet
Author: User

The array is the soul of PHP, very powerful, but sometimes object-oriented programming is also very convenient, the array and the switch between the object is often the case:

Example One

The code is as follows Copy Code

/**
* Array to Object
*
* Array $arr @param array
* @return Object
*/
function Array_to_object ($arr)
{
if (GetType ($arr)!= ' array ')
{
Return
}
foreach ($arr as $k => $v)
{
if (GetType ($v) = = ' Array ' | | GetType ($v) = = ' object ')
{
$arr [$k] = (object) array_to_object ($v);
}
}

Return (object) $arr;
}

/**
* Object to Array
*
* @param object $obj objects
* @return Array
*/
function Object_to_array ($obj)
{
$obj = (array) $obj;
foreach ($obj as $k => $v)
{
if (GetType ($v) = = ' Resource ')
{
Return
}
if (GetType ($v) = = ' object ' | | GetType ($v) = = ' array ')
{
$obj [$k] = (array) object_to_array ($v);
}
}

return $obj;
}

Example 2

The code is as follows Copy Code

<?php

Class test{
public $a;
Public $b;
Public function __construct ($a) {
$this->a = $a;
}
}

object to array, using Get_object_vars to return an array of object properties
function Objecttoarray ($obj) {
$arr = Is_object ($obj)? Get_object_vars ($obj): $obj;
if (Is_array ($arr)) {
Return Array_map (__function__, $arr);
}else{
return $arr;
}
}

Array to Object
function Arraytoobject ($arr) {
if (Is_array ($arr)) {
Return (object) Array_map (__function__, $arr);
}else{
return $arr;
}
}

$test = new Test (' test1 ');
$test->b = new Test (' test2 ');

Print_r ($test);
$array = Objecttoarray ($test);
Print_r ($array);
$object = Arraytoobject ($array);
Print_r ($object);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.