2014-02-17 34 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語言中更自然。