Querying Arrays

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?

13 comments

  1. 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.

  2. 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…

  3. 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.

  4. 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]

  5. 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

  6. 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);

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>