2013-09-23 34 views
2

我得到了下面的代碼片段,它工作得很好。我一直在分析它,並且這些代碼被使用了很多次,所以我想嘗試弄清楚如何以比當前寫入方式更好的方式編寫代碼。快速的方法做objectToArray

有沒有更有效的方法來寫這個?

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; 
    } 
} 
+1

轉換爲JSON,然後將轉換爲關聯數組? – MisterBla

回答

1

可以實現一個toArray()方法對需要轉換的類:

例如

class foo 
{ 
    protected $property1; 
    protected $property2; 

    public function __toArray() 
    { 
    return array(
     'property1' => $this->property1, 
     'property2' => $this->property2 
    ); 
    } 
} 

具有訪問受保護的特性,並具有封裝在類整體轉換在我看來是最好的方式。

更新

有一點要注意的是,get_object_vars()功能將只返回了公開訪問的性能 - 你可能不算什麼了。

如果上面太手工任務的準確方式從類的外部是使用PHP(SPL)建於ReflectionClass

$values = array(); 
$reflectionClass = new \ReflectionClass($object); 
foreach($reflectionClass->getProperties() as $property) { 
    $values[$property->getName()] = $property->getValue($object); 
} 
var_dump($values); 
+0

謝謝AlexP,能否把它放在當前片段的instad中? –

+0

@ChrisEdington看看我的更新。任何一個選項都可以工作,這取決於你試圖訪問變量的範圍,以及爲班級添加新方法的可行性。 – AlexP

+0

它能夠保持相同的功能結構和名稱,只是重寫裏面的代碼?正在轉換的對象是一個SOAP響應,如果有幫助的話。 –

0

取決於什麼樣的對象是,許多標準的PHP對象已經建立的方法將它們轉換

例如MySQLi的結果可以轉換這樣

$resultArray = $result->fetch_array(MYSQLI_ASSOC); 

如果你可能會考慮實施在類中的方法爲目的,AlexP自定義類對象sugested

+0

它能夠保持相同的功能結構和名稱,只是在裏面修改代碼?被轉換的對象是一個SOAP響應,如果有幫助的話...... –

+0

不是特別熟悉SOAP,而是一個快速的Google譴責它的XML,所以你可以使用PHP的XML函數 '$ soapResponce = simplexml_load_file(「soapResponce.xml」) ; (json_decode(json_encode((array)$ soapResponce),1)));} $ soapArray = unserialize(serialize(json_decode(json_encode((array)$ soapResponce),1))); print_r($ xml_array);' credit:http://stackoverflow.com/questions/12148662/xml-to-array-php – Philippe

0

結束了去:

function objectToArray($d) { 
$d = (object) $d; 
return $d; 
} 
function arrayToObject($d) { 
$d = (array) $d; 
return $d; 
} 
0

正如AlexP說,你可以實現一個方法__toArray() 。另外,以ReflexionClass(這是複雜和昂貴的),利用object iteration properties,你可以遍歷$this如下

class Foo 
{ 
    protected $var1; 
    protected $var2; 

    public function __toArray() 
    { 
    $result = array(); 
    foreach ($this as $key => $value) { 
     $result[$key] = $value; 
    } 
    return $result; 
    } 
} 

這也將迭代對象的屬性沒有在類中定義:例如

$foo = new Foo; 
$foo->var3 = 'asdf'; 
var_dump($foo->__toArray());) 

參見例如http://3v4l.org/OnVkf