php: convert an object to array

2019-11-09 2019-12-30 00:24:51 PHP,array,object,convert

Q: how to convert an object to array with php?

A: use the following recursive function convertObjectToArray to achieve this.

/**
 * @param mixed $mObject
 * @return array
 */
function convertObjectToArray($mObject)
{
    (is_object($mObject)) ? $mObject = (array) $mObject : false;

    if(is_array($mObject))
    {
        $aNew = array();

        foreach($mObject as $sKey => $mValue)
        {
            $sFirstChar = trim(substr(trim($sKey), 0, 1));
            (('*' === $sFirstChar)) ? $sKey = trim(substr(trim($sKey), 1)) : false;
            $aNew[$sKey] = convertObjectToArray($mValue);
        }
    }
    else
    {
        $aNew = $mObject;
    }

    return $aNew;
}

This website uses Cookies to provide you with the best possible service. Please see our Privacy Policy for more information. Click the check box below to accept cookies. Then confirm with a click on "Save".