Jump to: navigation, search

PHP Array Convert to Object

From w3cyberlearnings

Contents

PHP Array to Object

Convert array to object and for multiple arrays require to write a custom function to do the conversion recursively.

Example 1: Basic array

<?php

$actor = array(
	 'Greta Garbo',
	 'Andy Garcia',
	 'Ava Gardner',
	 'Lucy Johnson'
);

$obj_actor = (object) $actor;

print_r($obj_actor);
?>

Output


stdClass Object
(
    [0] => Greta Garbo
    [1] => Andy Garcia
    [2] => Ava Gardner
    [3] => Lucy Johnson
)

Example 2

  • Multiple array, need a custom function to convert an array to object recursively.
<?php

$my_experience = array(
	 'work', 'life', 'happy',
	 'happy2' => array('go out', 'race car', 'programming'),
	 'programming' => 'php'
);

$obj = arrayToObject($my_experience);

print_r($obj);

// custom function to convert the array recursively
function arrayToObject($d) {
	if (is_array($d)) {
		//recurse function
		return (object) array_map(__FUNCTION__, $d);
	} else {
		// Return object
		return $d;
	}
}

?>

Output

stdClass Object
(
    [0] => work
    [1] => life
    [2] => happy
    [happy2] => stdClass Object
        (
            [0] => go out
            [1] => race car
            [2] => programming
        )

    [programming] => php
)

Related Links


--PHP Array Introduction-- PHP Access Array-- PHP Array Convert to Object-- PHP Array Convert to JSON-- PHP Array Convert to Class-- PHP Array Convert to String--

Navigation
Web
SQL
MISC
References