PHP code example of athari / yalinqo

1. Go to this page and download the library: Download athari/yalinqo library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

athari / yalinqo example snippets



use \YaLinqo\Enumerable;

// 'from' can be called as a static method or via a global function shortcut
Enumerable::from([1, 2, 3]);
from([1, 2, 3]);

// Data
$products = [
    [ 'name' => 'Keyboard',    'catId' => 'hw', 'quantity' =>  10, 'id' => 1 ],
    [ 'name' => 'Mouse',       'catId' => 'hw', 'quantity' =>  20, 'id' => 2 ],
    [ 'name' => 'Monitor',     'catId' => 'hw', 'quantity' =>   0, 'id' => 3 ],
    [ 'name' => 'Joystick',    'catId' => 'hw', 'quantity' =>  15, 'id' => 4 ],
    [ 'name' => 'CPU',         'catId' => 'hw', 'quantity' =>  15, 'id' => 5 ],
    [ 'name' => 'Motherboard', 'catId' => 'hw', 'quantity' =>  11, 'id' => 6 ],
    [ 'name' => 'Windows',     'catId' => 'os', 'quantity' => 666, 'id' => 7 ],
    [ 'name' => 'Linux',       'catId' => 'os', 'quantity' => 666, 'id' => 8 ],
    [ 'name' => 'Mac',         'catId' => 'os', 'quantity' => 666, 'id' => 9 ],
];
$categories = [
    [ 'name' => 'Hardware',          'id' => 'hw' ],
    [ 'name' => 'Operating systems', 'id' => 'os' ],
];

// Put products with non-zero quantity into matching categories;
// sort categories by name;
// sort products within categories by quantity descending, then by name.
$result = from($categories)
    ->orderBy(fn($cat) => $cat['name'])
    ->groupJoin(
        from($products)
            ->where(fn($prod) => $prod['quantity'] > 0)
            ->orderByDescending(fn($prod) => $prod['quantity'])
            ->thenBy(fn($prod) => $prod['name'], 'strnatcasecmp'),
        fn($cat) => $cat['id'],
        fn($prod) => $prod['catId'],
        fn($cat, $prods) => [
            'name' => $cat['name'],
            'products' => $prods
        ]
    );

// More verbose syntax with parameter names (PHP 8.0+)
// and first-class callables (PHP 8.1+):
$result = Enumerable::from($categories)
    ->orderBy(keySelector: fn($cat) => $cat['name'])
    ->groupJoin(
        inner: from($products)
            ->where(predicate: fn($prod) => $prod['quantity'] > 0)
            ->orderByDescending(keySelector: fn($prod) => $prod['quantity'])
            ->thenBy(keySelector: fn($prod) => $prod['name'], comparer: strnatcasecmp(...)),
        outerKeySelector: fn($cat) => $cat['id'],
        innerKeySelector: fn($prod) => $prod['catId'],
        resultSelectorValue: fn($cat, $prods) => [
            'name' => $cat['name'],
            'products' => $prods
        ]
    );

print_r($result->toArrayDeep());