How to convert php array to object in loop

尊渡假赌尊渡假赌尊渡假赌
Release: 2023-08-10 14:44:04
Original
1015 people have browsed it

There are two methods for converting php arrays to objects in a loop: 1. Use forced type conversion to convert the array into an object, and the keys of the array must be valid object attribute names; 2. Create a new object , and copies the elements of the array into the object, independent of whether the array keys are valid as property names of the object.

How to convert php array to object in loop

Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.

To loop through a PHP array into an object, you can use cast or create a new object and copy the elements of the array.

Method 1: Forced type conversion

Use forced type conversion to convert an array into an object. It is required here that the keys of the array must be valid object property names.

$array = array(
    'name' => 'John',
    'age' => 30,
    'city' => 'New York'
);
obj=(object)obj = (object) obj=(object)array;
// 输出对象属性值
echo $obj->name; // 输出:John
echo $obj->age; // 输出:30
echo $obj->city; // 输出:New York
Copy after login

Method Two: Create a new object and copy the array elements

Another method is to create a new object and copies the elements of the array into the object. This method does not rely on whether the array key is valid as an object's property name.

$array = array(
    'name' => 'John',
    'age' => 30,
    'city' => 'New York'
);
$obj = new stdClass();
foreach (arrayasarray as arrayaskey => $value) {
    obj−>obj->obj−>key = $value;
}
// 输出对象属性值
echo $obj->name; // 输出:John
echo $obj->age; // 输出:30
echo $obj->city; // 输出:New York
Copy after login

Through the above two methods, you can convert PHP array loops into objects and easily access the object's property values.

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

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!