Created
September 10, 2015 20:29
-
-
Save dimzon/f3a0201a56b76bc2d5d8 to your computer and use it in GitHub Desktop.
MongoDB array tools (assoc <-> object consversions)
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 | |
class mongo_tools { | |
public static function assoc2obj($a){ | |
self::assoc2objects_inplace($a); | |
return $a; | |
} | |
public static function obj2assoc($o){ | |
self::objects2assoc_inplace($o); | |
return $o; | |
} | |
public static function assoc2objects_inplace(&$a){ | |
if(!is_array($a)) return; | |
if(count($a)===0) return; | |
foreach ($a as $key => &$value) { | |
self::assoc2objects_inplace($value); | |
} | |
if(!array_key_exists(0, $a)) $a = (object)$a; | |
} | |
public static function objects2assoc_inplace(&$a){ | |
if(is_object($a)){ | |
if(get_class($a)==='stdClass') | |
$a=(array)$a; | |
else | |
return; | |
} | |
if(!is_array($a)) return; | |
if(count($a)===1 && array_key_exists('$id', $a)){ | |
$a = new MongoId($a['$id']); | |
return; | |
} | |
foreach ($a as $key => &$value) { | |
self::objects2assoc_inplace($value); | |
} | |
} | |
} | |
$o=mongo_tools::assoc2obj(['A'=>['B'=>1337]]); | |
$a=mongo_tools::obj2assoc($o); | |
var_dump($a); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment