Php

PHPでstdClassオブジェクトを配列に変換する方法



How Convert Stdclass Object Array Php



Web開発では、フロントエンドとバックエンド間のデータの相互作用は通常jsonを介して実現されますが、PHPバックエンドからjsonを使用してフロントエンドに渡される配列は、標準の配列型ではなく、stdClass型です。操作するには、それを変換する必要があります。一般的な配列の場合、以下はいくつかの変換方法です。
方法1:

if(is_object($item)) { $toArray = (array)$item var_dump($toArray) }

方法2:



if(is_object($item)) { $toArray = json_decode( json_encode( $item),true) var_dump($toArray) }

方法3:

if(is_object($item)) { $toArray = get_object_vars($item) var_dump($toArray) }

get_object_varsの機能は、オブジェクト属性で構成される連想配列を返すことです。実際には、一般的な定義配列と同じです。



栗が来る

たとえば、データベースから一連のユーザー情報を取得してフロントエンドに送信しましたが、この情報のタイプはstdClass Objectであるため、上記の3つのメソッドを使用して通常の配列に変換しました。

    foreach ($data as $item):?>
  • if(is_object($item)) { $toArray = (array)$item echo 'array:' var_dump($toArray) $toArray1 = get_object_vars($item) echo 'get_object_vars:' var_dump($toArray1) echo 'json_decode:' $object = json_decode( json_encode( $item),true) var_dump($object) } ?>
  • endforeach?>

画像

stdClassについて

stdClass only started to be popular in PHP5, stdClass is also a reserved class of zend. stdClass is a base class of PHP. Almost all classes inherit this class, so it can be new at any time and this variable can be made an object. At the same time, this base class has a special place, that is, there is no method. Whenever using new stdClass() variables, it is impossible to use $a->test(). Or, we can understand it this way. Because of the uniqueness of PHP5 objects, the object is called anywhere, it is a reference address type, so the relative consumption of resources will be less. When assigning values ​​to it on other pages, it is modified directly, rather than a copy. We can understand it like this: stdClass is a built-in class that has no member variables and no member methods. A new stdClass instantiates an 'empty' object, which has no meaning in itself.