php簡(jiǎn)單對(duì)象與數(shù)組的轉(zhuǎn)換函數(shù)代碼(php多層數(shù)組和對(duì)象的轉(zhuǎn)換)
更新時(shí)間:2011年05月18日 00:05:27 作者:
最近用到一些簡(jiǎn)單的對(duì)象與數(shù)組的相互轉(zhuǎn)換的問(wèn)題,寫(xiě)個(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)容來(lái)自 cnblogs jaiho
php多層數(shù)組和對(duì)象的轉(zhuǎn)換
多層數(shù)組和對(duì)象轉(zhuǎn)化的用途很簡(jiǎn)單,便于處理WebService中多層數(shù)組和對(duì)象的轉(zhuǎn)化
簡(jiǎn)單的(array)和(object)只能處理單層的數(shù)據(jù),對(duì)于多層的數(shù)組和對(duì)象轉(zhuǎn)換則無(wú)能為力。
通過(guò)json_decode(json_encode($object)可以將對(duì)象一次性轉(zhuǎn)換為數(shù)組,但是object中遇到非utf-8編碼的非ascii字符則會(huì)出現(xiàn)問(wè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中的static和yield關(guān)鍵字
這篇文章主要給大家介紹了關(guān)于PHP中static和yield關(guān)鍵字的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用php具有一定的參考學(xué)習(xí)價(jià)值,文章需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09PHP中static關(guān)鍵字原理的學(xué)習(xí)研究分析
PHP中static關(guān)鍵字原理的學(xué)習(xí)研究分析,學(xué)習(xí)php的朋友可以參考下。2011-07-07PHP調(diào)試的強(qiáng)悍利器之PHPDBG
這篇文章主要為大家詳細(xì)介紹了PHP調(diào)試的強(qiáng)悍利器之PHPDBG的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-02-02php中的實(shí)現(xiàn)trim函數(shù)代碼
trim() 函數(shù)從字符串的兩端刪除空白字符和其他預(yù)定義字符。2007-03-03