codegooglecom / querytemplates

Automatically exported from code.google.com/p/querytemplates
0 stars 0 forks source link

Paths along arrays and objects #32

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
When using paths to access the data tree, it is possible in PHP that some
are arrays and some are objects, so there must be made a distinction
between more than 2 cases in the compiled script. This is how it currently
looks like for "varPrint('data.foo.bar.0')"

<div>
     <p><?php  if (isset($data['foo']['bar']['0'])) print
$data['foo']['bar']['0'];
 else if (isset($data->{'foo'}->{'bar'}->{'0'})) print
$data->{'foo'}->{'bar'}->{'0'};  ?></p>
 </div>

Solution:

function find ($object, array $path) {

    if (!$path) return $object;

    $next = array_shift($path);

    if (is_array($object)) return isset($object[$next]) ? find($object[$next],
$path) : null;
    elseif (is_object($object)) return isset($object->$next) ?
find($object->$next, $path) : null;
    else return $object;
}

$a = array();
$a[]=array();
$a[0]['OK'] = new stdclass;
$a[0]['OK']->test = 0;
$a[0]['OK']->c = 1;

var_dump(find($a, array(0, 'OK', 'c', 'a')));

And now it looks like: 

<div>
     <p><?php print(find($data, array('foo', 'bar', '0'))); ?></p>
</div>

Original issue reported on code.google.com by test9...@gmx.de on 28 Dec 2009 at 2:11