1. 程式人生 > >PHP簡單 對象(object) 與 數組(array) 的轉換

PHP簡單 對象(object) 與 數組(array) 的轉換

_array 轉換 blog cti style spa param obj 對象

 1 /**
 2  * 數組 轉 對象
 3  *
 4  * @param array $arr 數組
 5  * @return object
 6  */
 7 function array_to_object($arr) {
 8     if (gettype($arr) != ‘array‘) {
 9         return;
10     }
11     foreach ($arr as $k => $v) {
12         if (gettype($v) == ‘array‘ || getType($v) == ‘object‘) {
13 $arr[$k] = (object)array_to_object($v); 14 } 15 } 16 17 return (object)$arr; 18 } 19 20 /** 21 * 對象 轉 數組 22 * 23 * @param object $obj 對象 24 * @return array 25 */ 26 function object_to_array($obj) { 27 $obj = (array)$obj; 28 foreach ($obj as
$k => $v) { 29 if (gettype($v) == ‘resource‘) { 30 return; 31 } 32 if (gettype($v) == ‘object‘ || gettype($v) == ‘array‘) { 33 $obj[$k] = (array)object_to_array($v); 34 } 35 } 36 37 return $obj; 38 }

PHP簡單 對象(object) 與 數組(array) 的轉換