目錄
Using Type Casting (Simple Objects)
Handling Private and Protected Properties
Converting Nested Objects or Complex Data
首頁 後端開發 php教程 如何將對象轉換為PHP中的數組?

如何將對象轉換為PHP中的數組?

Sep 14, 2025 am 03:14 AM
php 陣列

使用(array)可將簡單對象轉為數組,若含私有或受保護屬性,鍵名會帶特殊字符;對於嵌套對象,應使用遞歸函數遍歷轉換,確保所有層級對像變為關聯數組。

How to convert an object to an array in PHP?

To convert an object to an array in PHP, you can use a simple type casting method or a recursive approach depending on the complexity of the object.

Using Type Casting (Simple Objects)

If the object contains only public properties and no nested objects, type casting with (array) works directly.

$object = new stdClass();
$object->name = "John";
$object->age = 30;

$array = (array) $object;
print_r($array);

This outputs:

Array
(
    [name] => John
    [age] => 30
)

Handling Private and Protected Properties

When an object has private or protected properties, casting to array includes additional characters in the keys to indicate visibility.

  • Private property myProp in class MyClass becomes "\0MyClass\0myProp"
  • Protected properties become "\0*\0propertyName"

This can complicate access, so consider using getters or reflection if you need clean array keys.

Converting Nested Objects or Complex Data

For objects containing other objects or arrays, a recursive function ensures full conversion.

function objectToArray($data) {
    if (is_object($data)) {
        $data = get_object_vars($data);
    }
    if (is_array($data)) {
        return array_map('objectToArray', $data);
    }
    return $data;
}

// Example usage
class Address {
    public $city = "New York";
    public $zip = "10001";
}

class Person {
    public $name = "Alice";
    public $address;
    
    public function __construct() {
        $this->address = new Address();
    }
}

$person = new Person();
$array = objectToArray($person);
print_r($array);

This approach ensures all levels of nested objects are converted into associative arrays.

Basically, use (array) for simple cases, and a recursive function when dealing with complex or nested objects.

以上是如何將對象轉換為PHP中的數組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

如何防止PHP中的跨站點偽造(CSRF)攻擊? 如何防止PHP中的跨站點偽造(CSRF)攻擊? Sep 11, 2025 pm 12:45 PM

ThemosteffectivewaytopreventCSRFattacksinPHPisusinganti-CSRFtokens.Generateasecuretokenviabin2hex(random_bytes(32)),storeitin$_SESSION,andincludeitasahiddenfieldinforms.Uponsubmission,verifythetokenmatchesthesessionvalue;rejectmismatches.Regenerateto

如何在PHP中的圖像中添加水印 如何在PHP中的圖像中添加水印 Sep 15, 2025 am 03:26 AM

使用PHP的GD庫可為圖片添加水印。首先加載原圖和水印(文字或圖像),再用imagecopy()或imagettftext()合併,最後保存輸出。支持JPEG、PNG等格式,注意處理透明度和字體路徑,確保GD擴展已啟用。

如何通過PHP中的定界符拆分字符串? 如何通過PHP中的定界符拆分字符串? Sep 11, 2025 pm 12:58 PM

使用explode()函數可按分隔符拆分字符串,其語法為explode(分隔符,字符串,限制數),例如explode(",","apple,banana")返回數組['apple','banana'];限制參數可控制返回元素數量,如explode("-","one-two-three",2)得['one','two-three'];若需多分隔符支持,則應用preg_split()配合正則表達式,如preg_split

如何將對象轉換為PHP中的數組? 如何將對象轉換為PHP中的數組? Sep 14, 2025 am 03:14 AM

使用(array)可將簡單對象轉為數組,若含私有或受保護屬性,鍵名會帶特殊字符;對於嵌套對象,應使用遞歸函數遍歷轉換,確保所有層級對像變為關聯數組。

如何防止PHP中的XSS(跨站點腳本)攻擊? 如何防止PHP中的XSS(跨站點腳本)攻擊? Sep 15, 2025 am 12:10 AM

dextxssbyescapingOutputwithHtmlSpecialChars()orjson_encode(),varyatingInputingFilter_var(),ApplivingCspheaders,andusingsecureframeworkslikelaravel。

如何在PHP中使用Curl進行API調用? 如何在PHP中使用Curl進行API調用? Sep 15, 2025 am 05:16 AM

初始izecurlwithcurl_init(),setOptionsLikeUrl,方法和檯面,senddatausingpostorcustormethods,handleressponseviacurl_exec(),checkerrorswithcurl_error(),retrievestatusatusususestatususingestatususisusiscusiscull_getInfo()

如何處理PHP中的環境變量? 如何處理PHP中的環境變量? Sep 15, 2025 am 03:55 AM

useeDenVoriablesandAndVlucas/phpdotenvtoload.envfilesIndeplepent; storessensitivedatalikeapikeysoutsidecode,nevercommit.envtoversioncontrol,andeectimentectualenvarionmentvariablesinblesinprododroductorityforsecurity。

如何在PHP中獲取發布數據? 如何在PHP中獲取發布數據? Sep 16, 2025 am 01:47 AM

使用$_POST超全局數組獲取POST數據,通過表單name屬性讀取值,處理數組輸入時用foreach循環,需驗證和過濾數據防止XSS。

See all articles