Skip to content

Instantly share code, notes, and snippets.

@trungx
Created August 27, 2019 16:34
Show Gist options
  • Save trungx/130048fa6eabea927f2455eec4451f19 to your computer and use it in GitHub Desktop.
Save trungx/130048fa6eabea927f2455eec4451f19 to your computer and use it in GitHub Desktop.
Recursive convert object to array
<?php
/* Recursive convert object to array
*
*
* @param object $variable
* @return converted array $variable
*/
function object_to_array($d) {
if (is_object($d))
$d = get_object_vars($d);
return is_array($d) ? array_map(__FUNCTION__, $d) : $d;
}
/**
* Recursive convert array to object
*
*
* @param array $variable
* @return converted object $variable
*/
function array_to_object($d) {
return is_array($d) ? (object) array_map(__FUNCTION__, $d) : $d;
}
$arr = [
"facebook"=>[
"ig"=>1,
"whatapps"=>2
],
"sv"=>"ssss",
"param" => [
"color"=>[
"red"=>1]
]
];
$encode = json_encode($arr);
//var_dump($encode);
$decode = json_decode($encode);
//var_dump($decode);
$res = object_to_array($decode);
var_dump($res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment