rpnzl/arrch

PHP 5.3 的数组查询

v1.1.1 2013-06-11 19:45 UTC

This package is not auto-updated.

Last update: 2024-09-23 10:48:53 UTC


README

一个用于数组查询、排序等的 PHP 库。

使用方法

Arrch 的主要方法 find() 是最常用的,它是 Arrch 的 where()sort() 和 limit/offset 选项的组合。where()sort() 在需要时也可以单独使用。

数据

我们需要一些数据来开始,最好是一个大型的对象数组或多维数组。以下是一个示例数组的截面...

// this is a LARGE array of multidimensional arrays
$data = array(
    ...,
    4037 => array(
        'name'  => array(
            'first' => 'Brian',
            'last'  => 'Searchable'
        ),
        'null'  => null,
        'age'   => 27,
        'email' => 'bsearchable@example.com',
        'likes' => array(
            'color' => 'blue',
            'food'  => 'cheese',
            'sauce' => 'duck'
        ),
    ),
    ...,
);

find() 方法

这可能是你使用最多的方法,默认配置如下。

Arrch\Arrch::find(
    $data, // array of multidimensional arrays
    $options = array(
        'where'         => array(),
        'limit'         => 0,
        'offset'        => 0,
        'sort_key'      => null, // dot notated array key or object property
        'sort_order'    => 'ASC' // 'ASC' or 'DESC'
    ),
    $key = 'all' // 'all', 'first', 'last', an index of the $data array
);

快速示例

确保将 arrch.php 文件包含在你的脚本或应用程序中。

include 'lib/arrch.php';

我们将使用 Arrch 尝试使用几个返回 Brian 数据 true 的条件来找到 Brian。你可以使用点 (.) 表示法遍历查询中的多维数组,并使用以下列出的一系列标准运算符来确定匹配。

// this query would find our Brian, plus any other Brians over age 25
// Remember that the Arrch class is part of the Arrch namespace
$results = Arrch\Arrch::find($data, array(

    'sort_key'  => 'name.last',
    'where'     => array(
        // tests for an exact match (===)
        array('name.first', 'Brian'),

        // use an operator
        array('age', '>', 25),
    ),

), 'first');

Where 条件

Arrch 条件相当灵活,可以想象成 MySQL 的 ANDORLIKEIN 运算符。首先,以下是一个有效运算符的列表。

// valid conditional operators
array('==', '===', '!=', '!==', '>', '<', '>=', '<=', '~');

其次,以下是一些有效条件的示例。

'where' => array(

    // OR statement
    array(array('name.first', 'likes.color'), 'blue'),

    // AND statement, including another condition
    array('age', '>', 25),

    // IN statement
    array('likes.food', array('toast', 'foie gras', 'cheese')),

    // OR/IN combined
    array(array('email', 'age'), array(27, 'goober@goob.co')),

    // Yes, you can compare to NULL
    array('null', null)

)

你可能想知道波浪号 (~) 运算符。这相当于 MySQL 的 LIKE 语句。你可以用它来检查字符串、数字的相似性,甚至确定关联数组键是否存在。

'where' => array(

    // First names that contain 'br'
    array('name.first', '~', 'br'),

    // Find folks that have a favorite food defined
    array('likes', '~', 'food')

)

限制

在大型生产环境中使用此库存在风险。在运行时内存中处理大型数组是一个缓慢的过程,在处理大量数据时可能会遇到严重的挂起。在这些情况下,为何不坚持使用合法的数据库接口和解决方案,如 PHP 核心扩展的 MySQL、PostgreSQL、MongoDB 等,以及相关的更成熟的抽象数据库库。

Arrch 可能会在小规模、平面文件存储环境中找到它的位置。当然,这个库可以与任何数据库解决方案一起使用,但你必须一次将整个集合加载到内存中才能对其查询。这可能不是好时机。

至少,用 PHP 的简单解决方案来玩很有趣,而无需使用 MySQL。但在开始之前,请务必诚实地了解你项目的需求!

许可证

MIT

作者

可在 rpnzl.comGitHubTwitter 上找到。