PHP multi-layered array and object conversions

Source: Internet
Author: User
Tags array arrays constant

The use of multilayer arrays and object transformations is simple and facilitates the processing of multilayer arrays and objects in webservice.

Simple (array) and (object) can only handle single layer of data, and for multiple layers of array and object conversion is powerless.

With Json_decode ($object) You can convert an object to an array at once, but there are problems with non-ASCII characters that are not utf-8 encoded in object, such as GBK Chinese, not to mention Json_ The performance of encode and Decode is also doubtful.

The following code:

 <?php   function Objecttoarray ($d) {if Is_object ($d)) {//Gets the properties of the given object
		With get_object_vars function $d = Get_object_vars ($d); }   if (Is_array ($d)) {* * return array converted to Object * Using __function__ (Magic constant) * F
		or recursive call */return Array_map (__function__, $d);
		else {//return array return $d; }   function Arraytoobject ($d) {if Is_array ($d)) {/* return array converted to Object * Using __f
		UNCTION__ (Magic constant) * For recursive call/Return (object) Array_map (__function__, $d);
		else {//return object return $d;
	}//Useage://Create new StdClass Object $init = new StdClass;
	ADD some test data $init->foo = "test Data";
	$init->bar = new StdClass;
	$init->bar->baaz = "testing";
	$init->bar->fooz = new StdClass;
	$init->bar->fooz->baz = "Testing Again"; $init,; foox = "Just test";
	 //Convert array to object and then object back to Array $array = Objecttoarray ($init);
$object = Arraytoobject ($array);
	 //Print objects and array print_r ($INIT);
	echo "\ n";
	Print_r ($array);
	echo "\ n"; 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.