PHP Classes

QArray PHP Query Array: Query hierarchic data stored as arrays

Recommend this page to a friend!
  Info   View files Documentation   View files View files (26)   DownloadInstall with Composer Download .zip   Reputation   Support forum (1)   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2022-08-08 (18 days ago) RSS 2.0 feedNot yet rated by the usersTotal: 43 This week: 1All time: 10,411 This week: 202Up
Version License PHP version Categories
qarray 1.0.0MIT/X Consortium ...5PHP 5, Searching, Data types
Description Author

This package can query hierarchic data stored as arrays.

It provides several classes that load an array and perform queries to find elements in the array that match certain conditions.

The query engine class returns an array with results with the path and values of the array elements that match the query conditions.

Applications can extend the query engine class to load array data, for instance, from a JSON string.

Picture of Nahid Bin Azhar
  Performance   Level  
Name: Nahid Bin Azhar <contact>
Classes: 19 packages by
Country: Bangladesh Bangladesh
Innovation award
Innovation award
Nominee: 5x

Winner: 2x

Details

QArray - Query Engine For Array

QArray is query engine for PHP array data. It helps to developers querying any kind of array data with ORM like feel.

Installation

composer require nahid/qarray

Implementation

Since QArray is an abstract layer of code, so you have to implement your own system with a lots of pre build functionality.

Lets start our first implementation for JSON data.

class JsonQueryEngine extends \Nahid\QArray\QueryEngine
{
    public function readPath($path)
    {
        $data = file_get_contents($path);

        return json_decode($data, true);
    }

    public function parseData($data)
    {
        return json_decode($data, true);
    }
}

Here you see we implement a new engine for JSON data. QueryEngine is an abstract class, so we have to implement its two abstract function readPath and parseData

Usage

Our implementation were complete, now we can use this implementation.

class Product
{
    protected $query;

    public function __construct(\Nahid\QArray\QueryEngine $query)
    {
        $this->query = $query;
    }

    public function getMacbook()
    {
        try {
            return $this->query
                ->from('.')
                ->where('cat', 2)
                ->get();
        } catch (\Exception $e) {
           return false;
        }

    }
}

Here we develop a class for Products and this class use JsonQueryEngine for fetch data from JSON file.

Lets see, how to use it.

here is our JSON file data.json

[
  {"id":1, "name":"iPhone", "cat":1, "price": 80000},
  {"id":2, "name":"macbook pro 2017", "cat": 2, "price": 210000},
  {"id":3, "name":"Redmi 3S Prime", "cat": 1, "price": 12000},
  {"id":4, "name":"Redmi 4X", "cat":1, "price": 15000},
  {"id":5, "name":"macbook air", "cat": 2, "price": 110000}
]

And now we read it to querying data.

$data = new JsonQueryEngine('data.json');
$query = new SomethingBuilder($data);

dump($query->getMacbook()->toArray());

Output

array:2 [
  1 => array:4 [
    "id" => 2
    "name" => "macbook pro 2017"
    "cat" => 2
    "price" => 210000
  ]
  4 => array:4 [
    "id" => 5
    "name" => "macbook air"
    "cat" => 2
    "price" => 110000
  ]
]

Pretty neat, huh?

Let's explore the full API to see what else magic this library can do for you. Shall we?

API

List of API:

Available operation for where clause

  • `key` -- the property name of the data. Or you can pass a Function here to group multiple query inside it. See details in example
  • `val` -- value to be matched with. It can be a _int_, _string_, _bool_ or even _Function_ - depending on the `op`.
  • `op` -- operand to be used for matching. The following operands are available to use:

    * `=` : For weak equality matching * `eq` : Same as `=` * `!=` : For weak not equality matching * `neq` : Same as `!=` * `==` : For strict equality matching * `seq` : Same as `==` * `!==` : For strict not equality matching * `sneq` : Same as `!==` > : Check if value of givenkeyin data is Greater thanval* * `gt` : Same as `>` < : Check if value of givenkeyin data is Less thanval* * `lt` : Same as `<` >= : Check if value of givenkeyin data is Greater than or Equal ofval* * `gte` : Same as `>=` <= : Check if value of givenkeyin data is Less than or Equal ofval* * `lte` : Same as `<=` null : Check if the value of givenkeyin data isnull* (`val` parameter in `where()` can be omitted for this `op`) notnull : Check if the value of givenkeyin data isnot null* (`val` parameter in `where()` can be omitted for this `op`) in : Check if the value of givenkeyin data is exists in givenval.val* should be a plain _Array_. notin : Check if the value of givenkeyin data is not exists in givenval.val* should be a plain _Array_. startswith : Check if the value of givenkeyin data starts with (has a prefix of) the givenval*. This would only works for _String_ type data. endswith : Check if the value of givenkeyin data ends with (has a suffix of) the givenval*. This would only works for _String_ type data. contains : Check if the value of givenkeyin data has a substring of givenval*. This would only works for _String_ type data. match : Check if the value of givenkeyin data has a Regular Expression match with the givenval. The val parameter should be aRegExp* for this `op`. * `instance` : Check it the value of given `key` in data has an instance.

example:

Let's say you want to find the _'users'_ who has _id_ of 1. You can do it like this:

$q = new Jsonq('data.json');
$res = $q->from('users')->where('id', '=', 1)->get();

You can add multiple _where_ conditions. It'll give the result by AND-ing between these multiple where conditions.

$q = new Jsonq('data.json');
$res = $q->from('users')
->where('id', '=', 1)
->where('location', '=', 'barisal')
->get();

See a detail example here.

orWhere(key, op, val)

Parameters of orWhere() are the same as where(). The only difference between where() and orWhere() is: condition given by the orWhere() method will OR-ed the result with other conditions.

For example, if you want to find the users with _id_ of 1 or 2, you can do it like this:

$q = new Jsonq('data.json');
$res = $q->from('users')
->where('id', '=', 1)
->orWhere('id', '=', 2)
->get();

See detail example here.

whereIn(key, val)

  • `key` -- the property name of the data
  • `val` -- it should be an Array

This method will behave like where(key, 'in', val) method call.

whereNotIn(key, val)

  • `key` -- the property name of the data
  • `val` -- it should be an Array

This method will behave like where(key, 'notin', val) method call.

whereNull(key)

  • `key` -- the property name of the data

This method will behave like where(key, 'null') or where(key, '=', null) method call.

whereNotNull(key)

  • `key` -- the property name of the data

This method will behave like where(key, 'notnull') or where(key, '!=', null) method call.

whereStartsWith(key, val)

  • `key` -- the property name of the data
  • `val` -- it should be a String

This method will behave like where(key, 'startswith', val) method call.

whereEndsWith(key, val)

  • `key` -- the property name of the data
  • `val` -- it should be a String

This method will behave like where(key, 'endswith', val) method call.

whereContains(key, val)

  • `key` -- the property name of the data
  • `val` -- it should be a String

This method will behave like where(key, 'contains', val) method call.

whereDataType(key, val)

  • `key` -- the property name of the data
  • `val` -- it should be a String

This method will behave like whereDataType(key, 'type', val) method call.

sum(column)

  • `column` -- the property name of the data

Bugs and Issues

If you encounter any bugs or issues, feel free to open an issue at github.

Also, you can shoot me an email to <mailto:nahid.dns@gmail.com> for hugs or bugs.

  Files folder image Files  
File Role Description
Files folder image.github (1 directory)
Files folder imagehelpers (1 file)
Files folder imagesrc (5 files, 1 directory)
Files folder imagetests (5 files, 1 directory)
Accessible without login Plain text file .travis.yml Data Auxiliary data
Accessible without login Plain text file changelog.txt Doc. Documentation
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file data.json Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file phpunit.xml.dist Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  .github  
File Role Description
Files folder imageworkflows (1 file)

  Files folder image Files  /  .github  /  workflows  
File Role Description
  Accessible without login Plain text file workflow.yml Data Auxiliary data

  Files folder image Files  /  helpers  
File Role Description
  Accessible without login Plain text file qarray.php Aux. Auxiliary script

  Files folder image Files  /  src  
File Role Description
Files folder imageExceptions (6 files)
  Plain text file ArrayQuery.php Class Class source
  Plain text file Clause.php Class Class source
  Plain text file ConditionFactory.php Class Class source
  Plain text file KeyNotExists.php Class Class source
  Plain text file QueryEngine.php Class Class source

  Files folder image Files  /  src  /  Exceptions  
File Role Description
  Plain text file ConditionNotAllowedException.php Class Class source
  Plain text file FileNotFoundException.php Class Class source
  Plain text file InvalidJsonException.php Class Class source
  Plain text file InvalidNodeException.php Class Class source
  Plain text file KeyNotPresentException.php Class Class source
  Plain text file NullValueException.php Class Class source

  Files folder image Files  /  tests  
File Role Description
Files folder imageFacades (1 file)
  Plain text file AbstractTestCase.php Class Class source
  Plain text file ConditionTest.php Class Class source
  Plain text file JsonqServiceProviderTest.php Class Class source
  Plain text file JsonQueriableTest.php Class Class source
  Plain text file TestCase.php Class Class source

  Files folder image Files  /  tests  /  Facades  
File Role Description
  Plain text file Jsonq.php Class Class source

 Version Control Unique User Downloads Download Rankings  
 100%
Total:43
This week:1
All time:10,411
This week:202Up
For more information send a message to info at phpclasses dot org.