Method of using recursion to implement transformations between PHP arrays and objects

Source: Internet
Author: User
Tags foreach arrays

The example of this article describes the method of using recursive implementations of PHP arrays and objects. Share to everyone for your reference. The implementation methods are as follows:

Here are some simple questions about the conversion of objects to arrays, using recursion to write two methods as follows:

?

1

2

3

4

5

6

7

8function Arraytoobject ($e) {

if (GetType ($e)!= ' array ') return;

foreach ($e as $k => $v) {

if (GetType ($v) = = ' Array ' | | GetType ($v) = = ' object ')

$e [$k]= (object) Arraytoobject ($v);

}

Return (object) $e;

}

?

1

2

3

4

5

6

7

8

9function Objecttoarray ($e) {

$e = (array) $e;

foreach ($e as $k => $v) {

if (GetType ($v) = = ' resource ') return;

if (GetType ($v) = = ' object ' | | GetType ($v) = = ' array ')

$e [$k]= (Array) Objecttoarray ($v);

}

return $e;

}

?

1

2

3

4

5

6

7

8function Object_to_array ($e) {

$_arr = Is_object ($e)? Get_object_vars ($e): $e;

foreach ($_arr as $key => $val) {

$val = (Is_array ($val) | | | is_object ($val))? Object_to_array ($val): $val;

$arr [$key] = $val;

}

return $arr;

}

I hope this article will help you with your PHP program design.

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.