Before I really get into it, I wanted to ask if anyone knew of a something already written in PHP to query arrays. Something kind of like:
[php]
$arr=array(
‘foo’=>array(
‘one’=>’this’,
‘two’=>’that’
)
);
$seek=’foo one’;
$query = new ArrayQuery($seek,$arr);
[/php]
…where $query would contain the node of key “one” and its contents, “this”. I’ve found myself needing something like this a few times recently, but haven’t been able to find something.
Does anyone know of anything like this or would find it useful in their own development work?
I think this is what you are looking for:
http://www.php.net/manual/en/function.array-search.php
LikeLike
Actually, it’s a bit more than that – more of a pattern patching rather than just looking for one certain value. So that “foo bar baz” only return results if there’s something that matches the key of “foo” with a subkey of “bar” with a subkey of “baz”.
The real key to what I want, though, is the ability to return something that’s the same as (with a regular expression) “foo bar[0-9]+ baz” with the potential of returning a set of indexes with their values.
LikeLike
This might be what you are looking for:
http://cvs.horde.org/co.php?f=framework%2FUtil%2FArray.php#l141
LikeLike
Similar, but it’d be nice if it was flexible enough to match on both keys and values like (borrowing from CSS selectors some):
foo bar baz[contains=’my test’]
that would rock…
LikeLike
It sounds somewhat like fQuery, a Drupal module by Steven Wittens.
http://drupal.org/project/fquery
LikeLike
Actually, that’s pretty close to what I need – thanks. It’ll be a good reference point to work from…
LikeLike
take a look here http://absynthe.is.free.fr/sql4array/
LikeLike
This concept would be extremely helpful because I find myself having to ‘query’ deeply nested arrays in a new web app that I’ve been developing. If this could work using CSS selector specs, it’s even better!
So far, I have yet to find a pre-written class or function that does this well. I’ll have a look at fQuery.
LikeLike
SDO_XML has the ability for you to use a xslt style query on an array object.
Its a pretty cool interface:
[php]
$graph [“//path/on/struct[objectmember=’foo’]”] = whatever;
[/php]
LikeLike
why waste a function call and do such long code like
$seek=‘foo one’;
$query = new ArrayQuery($seek,$arr);
The plain old PHP style $arr[‘foo’][‘one’] is much simpler and shorter, without doing a function call. Easy..
xaos
LikeLike
After reading your comment with the selectors, i understand your idea. forget about my previous comment.
LikeLike
Why not convert the array into DOM form and use existing XPath technologies to get the job done?
LikeLike
function QueryArray($search = null, $input = array())
{
$search = explode(‘|’, $search);
foreach ($search as $row)
{
$input = $input[$row];
}
return $input;
}
$search = ‘item2|subitem’;
$input = array(
‘item1’ => ‘item1’,
‘item2’ => array(
‘subitem’ => ‘subitem’,
),
);
echo QueryArray($search, $input);
LikeLike