Friday 26 July 2013

Converting Object to Array


Convert all objects to Array :

function objectToArray( $object ) {
    if( !is_object( $object ) && !is_array( $object ) ) {
        return $object;
    }
    if( is_object( $object ) ) {
        $object = (array) $object;
    }
    return array_map( 'objectToArray', $object );
}

(or)


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


Converting First object to Array :


function app_convertObjectToArray($objectValue) {
if (is_array ( $objectValue )) {
$arrayValue = $objectValue;
} else {
$arrayValue = array ();
if (isset ( $objectValue )) {
array_push ( $arrayValue, $objectValue );
}
}
return $arrayValue;
}


No comments: