Convert PHP object to associative array

2018-12-31 05:31发布

I'm integrating an API to my website which works with data stored in objects while my code is written using arrays.

I'd like a quick and dirty function to convert an object to an array.

标签: php arrays
27条回答
听够珍惜
2楼-- · 2018-12-31 06:33

Some impovements to the "well-knwon" code

/*** mixed Obj2Array(mixed Obj)***************************************/ 
static public function Obj2Array($_Obj) {
    if (is_object($_Obj))
        $_Obj = get_object_vars($_Obj);
    return(is_array($_Obj) ? array_map(__METHOD__, $_Obj) : $_Obj);   
} // BW_Conv::Obj2Array

Notice that if the function is member of a class (like above) you must change __FUNCTION__ to __METHOD__

查看更多
时光乱了年华
3楼-- · 2018-12-31 06:34

Here is some code:

function object_to_array($data) {
    if ((! is_array($data)) and (! is_object($data))) return 'xxx'; //$data;
    $result = array();

    $data = (array) $data;
    foreach ($data as $key => $value) {
        if (is_object($value)) $value = (array) $value;
        if (is_array($value)) 
        $result[$key] = object_to_array($value);
        else
            $result[$key] = $value;
    }

    return $result;
}
查看更多
步步皆殇っ
4楼-- · 2018-12-31 06:36

You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:

$array = json_decode(json_encode($nested_object), true);
查看更多
登录 后发表回答