Last active
February 6, 2018 09:44
-
-
Save muzfr7/0ad4de37b4a376afc4c8cc7c20e41ef7 to your computer and use it in GitHub Desktop.
Converts given Multi-dimensional Array to Object, using Recursive Function Approach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// A multi-dimensional array | |
$user = [ | |
'firstname'=>'Muzafar', | |
'lastname'=>'Jatoi', | |
'contacts'=>[ | |
[ | |
'mobile'=>'0500000000', | |
'email'=>'[email protected]', | |
], | |
[ | |
'mobile'=>'03000000000', | |
'email'=>'[email protected]', | |
] | |
] | |
]; | |
// Converts given multi-dimensional array into object recursively | |
function arrayToObject(array $arr) { | |
$obj = new stdClass(); | |
foreach ($arr as $key=>$value) { | |
if (is_array($value)) { | |
$obj->$key = arrayToObject($value); | |
}else{ | |
$obj->$key = $value; | |
} | |
} | |
return $obj; | |
} | |
$userObj = arrayToObject($user); | |
echo $userObj->firstname; // Muzafar | |
echo $userObj->contacts->{0}->mobile; // 0500000000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment