国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > PHP > 正文

php簡單對象與數(shù)組的轉(zhuǎn)換函數(shù)代碼(php多層數(shù)組和對象的轉(zhuǎn)換)

2024-05-04 23:18:44
字體:
供稿:網(wǎng)友

復(fù)制代碼 代碼如下:


function arrayToObject($e){
if( gettype($e)!='array' ) return;
foreach($e as $k=>$v){
if( gettype($v)=='array' || getType($v)=='object' )
$e[$k]=(object)arrayToObject($v);
}
return (object)$e;
}

function objectToArray($e){
$e=(array)$e;
foreach($e as $k=>$v){
if( gettype($v)=='resource' ) return;
if( gettype($v)=='object' || gettype($v)=='array' )
$e[$k]=(array)objectToArray($v);
}
return $e;
}


上面的內(nèi)容來自 cnblogs jaiho
php多層數(shù)組和對象的轉(zhuǎn)換
多層數(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的性能也值得疑慮。

下面上代碼:

復(fù)制代碼 代碼如下:


<?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);
?>


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 保靖县| 晋宁县| 洱源县| 西和县| 土默特右旗| 昭觉县| 微博| 边坝县| 淮安市| 卢氏县| 梓潼县| 合江县| 石城县| 红河县| 吉林市| 山西省| 高雄市| 翁牛特旗| 太仓市| 浑源县| 咸宁市| 库伦旗| 聂拉木县| 渝中区| 庄河市| 道孚县| 连江县| 陕西省| 尚义县| 平度市| 共和县| 隆尧县| 石嘴山市| 安丘市| 盐边县| 淄博市| 佛坪县| 濮阳县| 阿拉善右旗| 花莲县| 漳浦县|