今天就跟大家聊聊有關如何實現(xiàn)php對象轉數(shù)組函數(shù),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
官方文檔是這樣解釋的:
array get_object_vars ( object $obj )
返回由 obj 指定的對象中定義的屬性組成的關聯(lián)數(shù)組。
舉例:
x = $x; $this->y = $y; } function setLabel($label) { $this->label = $label; } function getPoint() { return array("x" => $this->x, "y" => $this->y, "label" => $this->label); } } // "$label" is declared but not defined $p1 = new Point2D(1.233, 3.445); print_r(get_object_vars($p1)); $p1->setLabel("point #1"); print_r(get_object_vars($p1)); ?>
輸出:
Array ( [x] => 1.233 [y] => 3.445 [label] => ) Array ( [x] => 1.233 [y] => 3.445 [label] => point #1 )
對象轉數(shù)組具體實現(xiàn):
function objectToArray($obj) { //首先判斷是否是對象 $arr = is_object($obj) ? get_object_vars($obj) : $obj; if(is_array($arr)) { //這里相當于遞歸了一下,如果子元素還是對象的話繼續(xù)向下轉換 return array_map(__FUNCTION__, $arr); }else { return $arr; } }
數(shù)組轉對象的具體實現(xiàn):
function arrayToObject($arr) { if(is_array($arr)) { return (object)array_map(__FUNCTION__, $arr); }else { return $arr; } }
看完上述內容,你們對如何實現(xiàn)php對象轉數(shù)組函數(shù)有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。