Safely Parse Complex Objects and Arrays in PHP
1 min read May 13, 2013
Support this website by purchasing prints of my photographs! Check them out here.
<?php
/**
* This class will safely parse complex objects or arrays with possible missing keys
*
* Usage: obj::query($obj, 'dot.separated.syntax');
*/
class obj {
/**
* Parse the provided object
*
* @param $object mixed The complex object you're going to parse
* @param $path string The dot separated path you would like to query the object with
*/
public static function query($object, $path) {
$paths = explode('.', $path);
return self::recurse($object, $paths);
}
/**
* The function that does the real work
*
* @param $object mixed
* @param $paths array
*/
protected static function recurse($object, $paths) {
if (!$object) {
return null;
}
if (!is_array($object) && !is_object($object)) {
return $object;
}
$newPath = array_shift($paths);
if (is_array($object) && isset($object[$newPath])) {
return self::recurse($object[$newPath], $paths);
} else if (is_object($object) && isset($object->$newPath)) {
return self::recurse($object->$newPath, $paths);
} else {
return null;
}
}
}
$data = '{
"x": {
"y": true,
"z": null,
"w": false,
"l": "banana",
"a": {
"b": {
"c": "d",
"d": "e"
}
}
}
}';
$complexArray = json_decode($data, true);
$complexObject = json_decode($data);
$complexMixed = array(
array(
'x' => json_decode('{"name": "so complex"}')
)
);
echo "Should be banana: ";
var_dump(obj::query($complexArray, 'x.l'));
echo "Should be 'e': ";
var_dump(obj::query($complexArray, 'x.a.b.d'));
echo "Should be NULL: ";
var_dump(obj::query($complexArray, 'a.b.c.d.e.f.g'));
echo "Should be TRUE: ";
var_dump(obj::query($complexObject, 'x.y'));
echo "Should be 'so complex': ";
var_dump(obj::query($complexMixed, '0.x.name'));
@tlhunter
I came here to kick ass, build web applications, and chew bubble gum. And I'm all out of gum.
My Books
External
Side Projects
📰
Affiliate Links