2014-02-17 19 views
4

我想知道是否有一个库实现类似SQL的接口来访问数组中的数据,例如是否有查询语言来过滤数组?

输入:

[ 
    ['name' => 'Tom', 'age' => 27, 'location' => ['country' => 'GB']], 
    ['name' => 'Jerry', 'age' => 16, 'location' => ['country' => 'LT']], 
    ['name' => 'Stuart', 'age' => 26, 'location' => ['country' => 'GB']] 
] 

虚构查询:

SELECT name, location.country FROM {input} WHERE age > 18 ORDER BY age DESC 

将产生的变化:

[ 
    ['name' => 'Tom', 'location.country' => 'GB'], 
    ['name' => 'Tom', 'location.country' => 'GB'] 
] 

注意,我完全知道array_filter和都实现,我可以当场放在一起。我正在寻找像接口一样的查询来访问数据。

回答

2

您可以使用LINQ,用PHP实现,如phpLinqLINQ for PHPplinq

+3

似乎每一个linq库已经停产。我想知道是否因为其他原因没有用。我在“linq”名下找到的最新实现是https://github.com/Athari/YaLinqo。另一个是在我的答案中提到的ArrayQuery。 – Gajus

0

我发现下面是最接近所有可用的替代品:

https://github.com/braincrafted/arrayquery

ArrayQuery不提供查询语言,尽管它确实提供了查询API,例如

$thorinsCompany = [ 
    [ 'name' => 'Bilbo Baggins', 'race' => 'Hobbit' ], 
    [ 'name' => 'Gandalf', 'race' => 'Wizard' ], 
    [ 'name' => 'Thorin Oakenshild', 'race' => 'Dwarf' ], 
    [ 'name' => 'Balin', 'race' => 'Dwarf'], 
    [ 'name' => 'Bifur', 'race' => 'Dwarf'], 
    // ... 
]; 

$query->from($thorinsCompany); 
$query->where('race', 'Dwarf') 
$query->where('age', 50, '>'); 
$results = $query->findAll(); 

相关提示,蒙戈PHP扩展提供SQL到Mongo的API翻译,http://www.php.net/manual/en/mongo.sqltomongo.php。基本的逻辑可以作为一个人指导开发PHP数组的SQL接口的例子。

0

我想为什么在PHP中没有任何积极使用的SQL类查询语言的原因是性能。使用类似ArrayQuery(我是其作者)已经导致性能损失。查询语言会导致性能进一步下降,这使得大部分时间没有意义。

ArrayQuery也受到Doctrines QueryBuilder的启发,这是一种将SQL转换为基于对象的方式,这种对象在PHP等OOP语言中更自然。