程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php簡單對象與數組的轉換函數代碼(php多層數組和對象的轉換)

php簡單對象與數組的轉換函數代碼(php多層數組和對象的轉換)

編輯:關於PHP編程

復制代碼 代碼如下:
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;
}

上面的內容來自 cnblogs jaiho
php多層數組和對象的轉換
多層數組和對象轉化的用途很簡單,便於處理WebService中多層數組和對象的轉化
簡單的(array)和(object)只能處理單層的數據,對於多層的數組和對象轉換則無能為力。
通過json_decode(json_encode($object)可以將對象一次性轉換為數組,但是object中遇到非utf-8編碼的非ascii字符則會出現問題,比如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);
?>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved