Skip to content

Instantly share code, notes, and snippets.

@muzfr7
Last active February 6, 2018 09:44
Show Gist options
  • Save muzfr7/0ad4de37b4a376afc4c8cc7c20e41ef7 to your computer and use it in GitHub Desktop.
Save muzfr7/0ad4de37b4a376afc4c8cc7c20e41ef7 to your computer and use it in GitHub Desktop.
Converts given Multi-dimensional Array to Object, using Recursive Function Approach
<?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