php多層數(shù)組與對象的轉(zhuǎn)換實(shí)例代碼
多層數(shù)組和對象轉(zhuǎn)化的用途很簡單,便于處理WebService中多層數(shù)組和對象的轉(zhuǎn)化
簡單的(array)和(object)只能處理單層的數(shù)據(jù),對于多層的數(shù)組和對象轉(zhuǎn)換則無能為力。
通過json_decode(json_encode($object)可以將對象一次性轉(zhuǎn)換為數(shù)組,但是object中遇到非utf-8編碼的非ascii字符則會出現(xiàn)問題,比如gbk的中文,何況json_encode和decode的性能也值得疑慮。
下面上代碼:
<?php
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
function arrayToObject($d) {
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return (object) array_map(__FUNCTION__, $d);
}
else {
// Return object
return $d;
}
}
// Useage:
// Create new stdClass Object
$init = new stdClass;
// Add some test data
$init->foo = "Test data";
$init->bar = new stdClass;
$init->bar->baaz = "Testing";
$init->bar->fooz = new stdClass;
$init->bar->fooz->baz = "Testing again";
$init->foox = "Just test";
// Convert array to object and then object back to array
$array = objectToArray($init);
$object = arrayToObject($array);
// Print objects and array
print_r($init);
echo "\n";
print_r($array);
echo "\n";
print_r($object);
?>
- PHP中把對象數(shù)組轉(zhuǎn)換成普通數(shù)組的方法
- php實(shí)現(xiàn)數(shù)組中索引關(guān)聯(lián)數(shù)據(jù)轉(zhuǎn)換成json對象的方法
- PHP數(shù)組與對象之間使用遞歸實(shí)現(xiàn)轉(zhuǎn)換的方法
- php對象和數(shù)組相互轉(zhuǎn)換的方法
- PHP中把對象轉(zhuǎn)換為關(guān)聯(lián)數(shù)組代碼分享
- 解析PHP將對象轉(zhuǎn)換成數(shù)組的方法(兼容多維數(shù)組類型)
- PHP對象轉(zhuǎn)換為數(shù)組函數(shù)(遞歸方法)
- php簡單對象與數(shù)組的轉(zhuǎn)換函數(shù)代碼(php多層數(shù)組和對象的轉(zhuǎn)換)
- PHP實(shí)現(xiàn)數(shù)組和對象的相互轉(zhuǎn)換操作示例
相關(guān)文章
php生成百度sitemap站點(diǎn)地圖類函數(shù)實(shí)例
這篇文章主要介紹了php生成百度sitemap站點(diǎn)地圖類函數(shù)的方法,詳細(xì)講述了百度站點(diǎn)sitemap的實(shí)現(xiàn)方法與注意事項(xiàng),在web站點(diǎn)的建設(shè)中非常具有實(shí)用價(jià)值,需要的朋友可以參考下2014-10-10php數(shù)組函數(shù)序列之sort() 對數(shù)組的元素值進(jìn)行升序排序
sort() 函數(shù)按升序?qū)o定數(shù)組的值排序。注釋:本函數(shù)為數(shù)組中的單元賦予新的鍵名。原有的鍵名將被刪除2011-11-11