Convert a PHP object to an associative array

后端 未结 30 1493
走了就别回头了
走了就别回头了 2020-11-22 02:18

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

30条回答
  •  隐瞒了意图╮
    2020-11-22 02:35

    Here is my recursive PHP function to convert PHP objects to an associative array:

    // ---------------------------------------------------------
    // ----- object_to_array_recursive --- function (PHP) ------
    // ---------------------------------------------------------
    // --- arg1: -- $object  =  PHP Object         - required --
    // --- arg2: -- $assoc   =  TRUE or FALSE      - optional --
    // --- arg3: -- $empty   =  '' (Empty String)  - optional --
    // ---------------------------------------------------------
    // ----- Return: Array from Object --- (associative) -------
    // ---------------------------------------------------------
    
    function object_to_array_recursive($object, $assoc=TRUE, $empty='')
    {
        $res_arr = array();
    
        if (!empty($object)) {
    
            $arrObj = is_object($object) ? get_object_vars($object) : $object;
    
            $i=0;
            foreach ($arrObj as $key => $val) {
                $akey = ($assoc !== FALSE) ? $key : $i;
                if (is_array($val) || is_object($val)) {
                    $res_arr[$akey] = (empty($val)) ? $empty : object_to_array_recursive($val);
                }
                else {
                    $res_arr[$akey] = (empty($val)) ? $empty : (string)$val;
                }
                $i++;
            }
        }
        return $res_arr;
    }
    
    // ---------------------------------------------------------
    // ---------------------------------------------------------
    

    Usage example:

    // ---- Return associative array from object, ... use:
    $new_arr1 = object_to_array_recursive($my_object);
    // -- or --
    // $new_arr1 = object_to_array_recursive($my_object, TRUE);
    // -- or --
    // $new_arr1 = object_to_array_recursive($my_object, 1);
    
    
    // ---- Return numeric array from object, ... use:
    $new_arr2 = object_to_array_recursive($my_object, FALSE);
    

提交回复
热议问题