How to convert php array to obj

PHPz
Release: 2023-04-23 13:46:03
Original
837 people have browsed it

In PHP, arrays and objects are both used to store multiple data, but the ways of using them are still different. When we need to convert an array into an object, we can use the type conversion method that comes with PHP, or we can write our own code to implement it.

There are two main ways to convert arrays into objects in PHP:

1. Use (object) forced type conversion

In PHP, we can use (object ) casts an array type to an object type. This method is very simple, just add (object) in front of the array to convert it into an object.

The example is as follows:

$arr = array('name' => 'John', 'age' => 30);
$obj = (object) $arr;
Copy after login

After using forced type conversion to convert the array into an object, you can use the object method to access the array elements, as follows:

echo $obj->name; // 输出:John
echo $obj->age; // 输出:30
Copy after login

2. Manual conversion using typecasting

In addition to forced type conversion, we can also convert an array into an object by manually performing type conversion.

The example is as follows:

$arr = array('name' => 'John', 'age' => 30);
$obj = new stdClass();

foreach ($arr as $key => $value) {
    $obj->$key = $value;
}
Copy after login

In the above example, we first create an empty stdClass object, and then assign the key-value pair of the element to the object property by traversing the array elements. The resulting $obj object is exactly the same as the object obtained using the cast.

Summary

In PHP, converting an array into an object is very simple. We can use forced type conversion or manual type conversion to achieve it. By converting arrays into objects, we can more conveniently manipulate array elements and achieve more flexible data processing.

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

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