PHP conversion Array

Source: Internet
Author: User
Tags smarty template

The foreach of the smarty template does not support objects, but only arrays. For JSON data, you can only convert it to an array before using foreach.

One of the conversion methods is to directly use (array), such:

$ Array = (array) $ OBJ;

After testing, this method only supports one layer of data structure. For $ obj-> obj1-> obj2, such data cannot be converted.

The second method of conversion is to compile Recursive Function Conversion, for example:

/**
* Convert objects to Arrays
*
* @ Param object $ OBJ
* @ Return Array
*/
Function object_to_array ($ OBJ)
{
$ _ Arr = is_object ($ OBJ )? Get_object_vars ($ OBJ): $ OBJ;
Foreach ($ _ arr as $ key => $ Val)
{
$ Val = (is_array ($ Val) | is_object ($ Val ))? Object_to_array ($ Val): $ val;
$ Arr [$ key] = $ val;
}
Return $ arr;
}

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.