php簡單對象與數(shù)組的轉(zhuǎn)換函數(shù)代碼(php多層數(shù)組和對象的轉(zhuǎn)換)
更新時(shí)間:2011年05月18日 00:05:27 作者:
最近用到一些簡單的對象與數(shù)組的相互轉(zhuǎn)換的問題,寫個(gè)兩個(gè)方法如下,需要的朋友可以參考下。
復(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字符則會(huì)出現(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);
?>
相關(guān)文章
PHP得到mssql的存儲(chǔ)過程的輸出參數(shù)功能實(shí)現(xiàn)
在開發(fā)過程中可能會(huì)遇到無法取得MSSQL存儲(chǔ)過程的輸出參數(shù),很多朋友都不知道該怎么辦,本文將詳細(xì)介紹PHP得到mssql的存儲(chǔ)過程的輸出參數(shù)功能實(shí)現(xiàn)2012-11-11
php連接oracle數(shù)據(jù)庫及查詢數(shù)據(jù)的方法
這篇文章主要介紹了php連接oracle數(shù)據(jù)庫及查詢數(shù)據(jù)的方法,以實(shí)例形式較為詳細(xì)的分析了php操作oracle數(shù)據(jù)庫的使用技巧,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2014-12-12
php中實(shí)現(xiàn)xml與mysql數(shù)據(jù)相互轉(zhuǎn)換的方法
這篇文章主要介紹了php中實(shí)現(xiàn)xml與mysql數(shù)據(jù)相互轉(zhuǎn)換的方法,實(shí)例封裝了一個(gè)類文件,可實(shí)現(xiàn)XML與MySQL數(shù)據(jù)的相互轉(zhuǎn)換,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2014-12-12
php實(shí)現(xiàn)快速對二維數(shù)組某一列進(jìn)行組裝的方法小結(jié)
這篇文章主要介紹了php實(shí)現(xiàn)快速對二維數(shù)組某一列進(jìn)行組裝的方法,涉及PHP數(shù)組遍歷、轉(zhuǎn)換、拆分等相關(guān)操作技巧,需要的朋友可以參考下2019-12-12

