Skip to content

Instantly share code, notes, and snippets.

@aholmes
Last active January 2, 2016 14:49
Show Gist options
  • Save aholmes/8319662 to your computer and use it in GitHub Desktop.
Save aholmes/8319662 to your computer and use it in GitHub Desktop.
The OOP version of https://igor.io/2014/01/08/functional-library-traversal.html for ghits and shiggles.
<?php
class Traverse implements ArrayAccess {
protected $container;
function __construct($array) {
$this->container = $array;
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetGet($offset) {
if (isset($this->container[$offset])) {
if (is_array($this->container[$offset])) {
$this->container[$offset] = new Traverse($this->container[$offset]);
}
return $this->container[$offset];
}
return null;
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = is_array($value) ? new Traverse($value) : $value;
}
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function __get($offset) {
return $this->offsetGet($offset);
}
}
class JSONTraverse extends Traverse {
function __construct($json, $assoc = false, $depth = 512, $options = 0) {
if (PHP_VERSION_ID < 50400) {
parent::__construct((array)json_decode($json, $assoc, $depth));
} else {
parent::__construct((array)json_decode($json, $assoc, $depth, $options));
}
}
public function offsetGet($offset) {
if ($this->container[$offset] instanceof stdClass) {
$this->container[$offset] = (array)$this->container[$offset];
}
return parent::offsetGet($offset);
}
}
$data = array('a'=>'-a','b'=>'-b','c' => array('x'=>-1,'y'=>-2,'z'=>-3), 'd'=>'-d');
$jsonData = '{"a":"-a","b":"-b","c":{"x":-1,"y":-2,"z":-3},"d":"-d"}';
echo "Array Traverse\n";
echo "--------------\n";
$t = new Traverse($data);
var_dump($t['c']['x']);
var_dump($t['c']['x']['y']);
var_dump($t->c->x);
// NOTICE - can't get 'y' index of integer value -1
var_dump($t->c->x->y);
echo "\nJSON Traverse\n";
echo "-------------\n";
$t = new JSONTraverse($jsonData);
var_dump($t['c']['x']);
var_dump($t['c']['x']['y']);
var_dump($t->c->x);
// NOTICE - can't get 'y' index of integer value -1
var_dump($t->c->x->y);
echo "\igor.io test\n";
echo "-----------\n";
$data = array(
'foo' => array(
'bar' => array(
'baz' => 'Ya got me!'
)
)
);
$t = new Traverse($data);
var_dump($t['foo']['bar']['baz']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment