asimlqt/arrayquery
数组查询
dev-master
2014-05-28 23:07 UTC
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2024-09-24 06:40:52 UTC
README
ArrayQuery是一个库,用于查询、分组和排序存储在嵌套PHP数组格式中的数据。
示例
use Asimlqt\ArrayQuery\Input\ArrayOfArrays; use Asimlqt\ArrayQuery\Query; $data = array( array( 'continent' => 'Europe', 'country' => 'England', 'city' => 'London', 'population' => '8000000' ), array( 'continent' => 'Europe', 'country' => 'France', 'city' => 'Paris', 'population' => '2200000' ), array( 'continent' => 'Asia', 'country' => 'Japan', 'city' => 'Tokyo', 'population' => '13200000' ), ); $source = new ArrayOfArrays($data); $query = new Query($source); $query->where(function($row) { return $row['population'] > 5000000; }); print_r($query->getResult());
API
select($columns)
Select类似于SQL查询中的select,它只保留传递给方法中的列并丢弃所有其他列。这通常在查询所需数据后、调用getResult()之前进行。一旦调用select,就不能过滤或查询已通过select移除的行,因为它们已不存在。
$query->select(array('city', 'population'));
filter($column, array $values)
Filter移除不包含指定值之一的列。它类似于MySQL中的"WHERE IN"子句。
$query->filter('city', array('London', 'Paris'));
where($closure)
where函数提供了以用户喜欢的方式过滤数据的自由度。闭包接受当前行并必须返回true或false。如果函数返回布尔值true,则该行将被保留,任何其他值将导致该行被移除。
$query->where(function($row) { return $row['population'] > 5000000; });
groupBy($columns, $closure)
允许对数据进行分组,以便每个指定列值的唯一集合只有一个行。
$query->groupBy(array('continent', 'country'));
您可以可选地指定闭包作为第二个参数。如果指定闭包,则每次找到指定列的重复行时都会调用它。返回值必须是一行。例如:
$query->groupBy(array('continent', 'country'), function($oldRow, $newRow) { $oldRow['population'] += $newRow['population']; return $oldRow; });
orderBy(array $order)
允许按一列或多列对数据进行排序。数组的关键字是列名,值是SORT_ASC或SORT_DESC。
$query->orderBy(array('continent' => SORT_ASC, 'population' => SORT_DESC));