Posted by & filed under PHP.

<?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'));

Thomas Hunter II

Thomas is the author of Advanced Microservices and a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.