Answers for "convert multidimensional array to object php"

PHP
0

php convert multidimensional object to array

$person = new stdClass();
$person->firstName = "Taylor";
$person->age = 32;

//Convert Single-Dimention Object to array
$personArray = (array) $person;

//Convert Multi-Dimentional Object to Array
$personArray = objectToArray($person);
function objectToArray ($object) {
    if(!is_object($object) && !is_array($object)){
    	return $object;
    }
    return array_map('objectToArray', (array) $object);
}
Posted by: Guest on November-03-2019
0

php convert object to array multidimensional

// Very fast way (More at pereere.com/php)
$obj = json_decode( json_encode( $obj ), true );


// Recursive Method
// Dont create function if it already exist
	if ( ! function_exists( 'convert_object_to_array' ) ) {

		/**
		 * Converts an object to an array recursively.
		 *
		 * @param  object  $obj  The object to convert
		 * @param  array   $arr  Recursive
		 *
		 * @return mixed
		 *
		 */
		function convert_object_to_array( $obj, &$arr = [] ) {

			// Return if @var $obj is not an object (may be an array)
			if ( ! is_object( $obj ) && ! is_array( $obj ) ) {
				$arr = $obj;

				return $arr;
			}

			foreach ( $obj as $key => $value ) {
				if ( ! empty( $value ) ) {
					$arr[ $key ] = array();
					// Recursively get convert the value to array as well
					convert_object_to_array( $value, $arr[ $key ] );
				} else {
					$arr[ $key ] = $value;
				}
			}

			return $arr;
		}
	}
Posted by: Guest on August-11-2021

Code answers related to "convert multidimensional array to object php"

Browse Popular Code Answers by Language