php簡單對象與數(shù)組的轉(zhuǎn)換函數(shù)代碼(php多層數(shù)組和對象的轉(zhuǎn)換)
更新時間:2011年05月18日 00:05:27 作者:
最近用到一些簡單的對象與數(shù)組的相互轉(zhuǎn)換的問題,寫個兩個方法如下,需要的朋友可以參考下。
復(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);
?>
相關(guān)文章
深入理解PHP中的static和yield關(guān)鍵字
這篇文章主要給大家介紹了關(guān)于PHP中static和yield關(guān)鍵字的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用php具有一定的參考學(xué)習(xí)價值,文章需要的朋友們下面隨著小編來一起學(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-02