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

How to convert php object array to ordinary array

藏色散人
藏色散人Original
2022-12-26 09:21:074010browse

How to convert php object array to a normal array: 1. Open the corresponding php file; 2. Use the "function std_class_object_to_array($stdclassobject){...}" method to convert the object array into a normal array.

How to convert php object array to ordinary array

The operating environment of this tutorial: windows10 system, PHP8.1 version, DELL G3 computer

How to convert php object array to ordinary array ?

php converts the object array into a normal array

I recently used ThinkPHP to develop an application for the JD service market. However, the data returned by the JD service market interface is Array of objects. However, you need to take out the attributes one by one and put them into the array and then use ThinkPHP's addAll or add method to write them to the database. However, there are dozens of fields returned each time, and it will collapse every time it is spliced ​​like this. Sure enough, it's still the same sentence, when you feel that you can't stand it, you will find a way to change it. So I thought about it, if there was a function that could automatically convert an object array into a normal array. So the universal internet search is back. Baidu made a pass. . . Sure enough, some seniors have already dealt with it, so I will record it here.

/**
* [std_class_object_to_array 将对象转成数组]
* @param [stdclass] $stdclassobject [对象]
* @return [array] [数组]
*/
function std_class_object_to_array($stdclassobject)
{
  $_array = is_object($stdclassobject) ? get_object_vars($stdclassobject) : $stdclassobject;
  foreach ($_array as $key => $value) {
    $value = (is_array($value) || is_object($value)) ? std_class_object_to_array($value) : $value;
    $array[$key] = $value;
  }
  return $array;
}

In this way, the object array is elegantly converted into an ordinary array. Using my brain, the code size was reduced and the functions were implemented elegantly. Kill two birds with one stone, why not?

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to convert php object array to ordinary array. 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