Home  >  Article  >  Backend Development  >  How to convert object to array in php

How to convert object to array in php

王林
王林Original
2020-10-30 14:24:185536browse

php method to convert an object into an array: 1. Get the object; 2. Define an empty array; 3. Loop through the object and assign a value to the array, such as [foreach ($obj as $key = > $value){$data[$key]=$value;}].

How to convert object to array in php

Ideas:

1. Get the object;

2. Define an empty array;

3. Loop through the objects and assign values ​​to the array.

(Recommended tutorial: php video tutorial)

Code implementation:

// 获取对象
$obj = (object) array('1' => 'foo','2'=>'goo',3=>'hoo');
 
// 定义空数组
$data = array();
 
// 循环遍历对象,对数组赋值
foreach ($obj as $key => $value) {
	$data[$key] = $value;
}
 
// 打印数组
var_dump($data);

Result:

How to convert object to array in php

Related recommendations: php training

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

Statement:
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