Skip to content

Instantly share code, notes, and snippets.

@dimzon
Created September 10, 2015 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimzon/f3a0201a56b76bc2d5d8 to your computer and use it in GitHub Desktop.
Save dimzon/f3a0201a56b76bc2d5d8 to your computer and use it in GitHub Desktop.
MongoDB array tools (assoc <-> object consversions)
<?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