您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“php如何將對(duì)象轉(zhuǎn)成數(shù)組”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
php將對(duì)象轉(zhuǎn)成數(shù)組的方法:1、創(chuàng)建一個(gè)php示例文件;2、將對(duì)象數(shù)組使用“json_encode”函數(shù)轉(zhuǎn)化為字符串;3、使用“json_decode”再轉(zhuǎn)為數(shù)組即可。
開發(fā)過(guò)程中我們會(huì)遇到需要將實(shí)例化的對(duì)象轉(zhuǎn)化為數(shù)組的情況
例如我想將處理過(guò)后的數(shù)據(jù)進(jìn)行excel導(dǎo)出但是excel導(dǎo)出只
支持?jǐn)?shù)組格式類型
例子
例如下面這個(gè)代碼我需要返回值data為數(shù)組類型,
雖然序列化為數(shù)組但是此時(shí)返回的是對(duì)象數(shù)組
$data=$orderList->getCollection()->map(function ($order){
return new OrderResponse($order);
});
dd($data->toArray());
返回如下
^ array:8 [
0 => app\admin\Responses\OrderResponse {#122
+"statistical_date": "2021-09-10"
+"order_num": 1
+"play_type_count": 1
+"invalid_order_count": 1
}
1 => app\admin\Responses\OrderResponse {#119
+"statistical_date": "2021-09-09"
+"order_num": 6
+"play_type_count": 6
+"invalid_order_count": 3
}
]
利用json_decode() 將字符串轉(zhuǎn)化為數(shù)組
先將對(duì)象數(shù)組使用json_encode轉(zhuǎn)化為字符串然后再轉(zhuǎn)為數(shù)組即可
$data=json_decode(json_encode($data),true);
array:8 [
0 => array:4 [
"statistical_date" => "2021-09-10"
"order_num" => 1
"play_type_count" => 1
"invalid_order_count" => 1
]
1 => array:4 [
"statistical_date" => "2021-09-09"
"order_num" => 6
"play_type_count" => 6
"invalid_order_count" => 3
]
]
“php如何將對(duì)象轉(zhuǎn)成數(shù)組”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。