Code Monkey home page Code Monkey logo

yalinqo's Introduction

GitHub created at GitHub followers GitHub following Time zone: UTC+3 (MSK) Native language: C#
Spoken language: C, C++, JavaScript, PHP, Python, Java, Visual Basic, SQL, HTML, CSS, Delphi, PowerShell, Lua
Human created: English, Russian Human language: English, Russian Gender: male Pronouns: взаимное ты, он, his
Education: specialist, KPFU, IoCMaIT Alignment: chaotic neutral Political views: civil libertarianism
E-mail: athari.p (cat with a curly tail) gmail.com Telegram: @Athari_P Skype: @Athari_P Stack Overflow: Athari Хабрахабр: Athari
Flairs: 1 Badges: 20

StackExchange flair

yalinqo's People

Contributors

athari avatar lucasjsoliveira avatar sanmai avatar zquintana avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yalinqo's Issues

Distinct returns incorrect indexes

After using distinct() on a collection of ids, the indexes of those distinct ids are exactly the first index where the value is encountered. Normally, I think one would expect them to be from 0 to N-1 ( N being the number of distinct values ).

I just found out it's not only distinct. Returned result sets's indexes are the same ones from their previous collection.

Using with PDO MySQL - a datetime example

hi there,

Im using it also to 'query' date/datetime field, in example an array from PDO MySQL, works flawless... :)
not optimized the manual dates (2017-02-12/2017-02-15) should be stored on vars, out of the loop.

$result3 = from($rows)
->where(function ($x) { return
strtotime($x['datecreated']) >= strtotime("2017-02-12") && 
strtotime($x['datecreated']) < strtotime("2017-02-15"); })
->select(function($res){ return array(
            "country" => $res['country'],
            "datecreated" => $res['datecreated']
        ); })
->toArray();

and also advise that can be used without composer :

require_once('/YaLinqo/Utils.php');
require_once('/YaLinqo/Functions.php');
require_once('/YaLinqo/Linq.php');
require_once('/YaLinqo/EnumerablePagination.php');
require_once('/YaLinqo/EnumerableGeneration.php');
require_once('/YaLinqo/Enumerable.php');
require_once('/YaLinqo/Errors.php');
require_once('/YaLinqo/OrderedEnumerable.php');

for groupby - check also - https://gist.github.com/mcaskill/baaee44487653e1afc0d

thanks for your time!

Improve performance when working with arrays

Implementations of some methods can be replaced with a single call to built-in functions if underlying iterator is wrapping an array, for example toValues, toKeys, max etc. Use built-in functions whenever possible.

Distinct filtering support

I have a nested array of strings:

array (size=9)
  0 => 
    array (size=5)
      0 => string 'configuration' (length=13)
      1 => string 'environment' (length=11)
      2 => string 'pagodabox' (length=9)
      3 => string 'php' (length=3)
      4 => string 'wordpress' (length=9)
  1 => 
    array (size=7)
      0 => string 'ckeditor' (length=8)
      1 => string 'configuration' (length=13)
      2 => string 'css' (length=3)
      3 => string 'drupal' (length=6)
      4 => string 'module' (length=6)
      5 => string 'php' (length=3)
      6 => string 'wysiwyg' (length=7)
  2 => 
    array (size=5)
      0 => string 'css' (length=3)
      1 => string 'drupal' (length=6)
      2 => string 'php' (length=3)
      3 => string 'stylesheets' (length=11)
      4 => string 'theming' (length=7)

This is generated by using select, so I've tried selectMany and get the following:

array (size=51)
  0 => string 'configuration' (length=13)
  1 => string 'environment' (length=11)
  2 => string 'pagodabox' (length=9)
  3 => string 'php' (length=3)
  4 => string 'wordpress' (length=9)
  5 => string 'ckeditor' (length=8)
  6 => string 'configuration' (length=13)
  7 => string 'css' (length=3)
  8 => string 'drupal' (length=6)
  9 => string 'module' (length=6)
  10 => string 'php' (length=3)
  11 => string 'wysiwyg' (length=7)
  12 => string 'css' (length=3)
  13 => string 'drupal' (length=6)
  14 => string 'php' (length=3)
  15 => string 'stylesheets' (length=11)
  16 => string 'theming' (length=7)
  17 => string 'environment' (length=11)
  18 => string 'mac' (length=3)
  19 => string 'mamp' (length=4)
  20 => string 'mamp pro' (length=8)
  21 => string 'mysql' (length=5)
  22 => string 'php' (length=3)
  23 => string 'phpmyadmin' (length=10)
  24 => string 'upgrade' (length=7)
  25 => string 'alphabet' (length=8)
  26 => string 'characters' (length=10)
  27 => string 'php' (length=3)
  28 => string 'range' (length=5)
  29 => string 'snippet' (length=7)
  30 => string 'extension' (length=9)
  31 => string 'mac' (length=3)
  32 => string 'mamp' (length=4)
  33 => string 'mamp pro' (length=8)

How can I get all distinct or unique values after selectMany?

Abandoned?

Is there any motivation from the maintainers to continue this lib? As it currently stands there are PHP 8 and 8.1 issues. PHP 7.4 is only receiving security support and that's expiring in 11 months. PHP 7.3 is EOL in 3 days, no longer receiving any security updates.

Enumerable::getIterator fails silently

For some reason, when calling toArray, which called getIterator, the script is failing silently. I've confirmed the array being passed to from is okay. It is a fairly deeply nested array with many objects.

I guess the real question here is... what's preventing exceptions?

Examples?

Why aren't there any examples? I get that this is a port of LINQ and many people may be familiar, but I am not and would like to use this lib. I appreciate the elegance of LINQ in filtering datasets, and PHP doesn't really have anything natively or other libs much for this.

I'm trying to pass from a Doctrine Collection object. Then call first(). However, I'm getting Sequence contains no matching elements.. Why?

how to 'sum my data'

hello Alexander Prokhorov,
I like YaLinqo and it make my work more efficient.
But it's difficult when I 'sum my data'
The array is as follows, I want to group by catId and sum up quantity

$products = array(
    array('name' => 'Keyboard',    'catId' => 'hw', 'quantity' =>  10, 'id' => 1),
    array('name' => 'Mouse',       'catId' => 'hw', 'quantity' =>  20, 'id' => 2),
    array('name' => 'Monitor',     'catId' => 'hw', 'quantity' =>   0, 'id' => 3),
    array('name' => 'Joystick',    'catId' => 'hw', 'quantity' =>  15, 'id' => 4),
    array('name' => 'CPU',         'catId' => 'hw', 'quantity' =>  15, 'id' => 5),
    array('name' => 'Motherboard', 'catId' => 'hw', 'quantity' =>  11, 'id' => 6),
    array('name' => 'Windows',     'catId' => 'os', 'quantity' => 666, 'id' => 7),
    array('name' => 'Linux',       'catId' => 'os', 'quantity' => 666, 'id' => 8),
    array('name' => 'Mac',         'catId' => 'os', 'quantity' => 666, 'id' => 9),
);

new array like this

$products = array(
    'hw' => [
        ‘catId’ => ‘hw’,
        ‘quantity_sum’ => ‘xxx’,
    ], 
    'os'=>[
        ‘catId’ => ‘os’,
        ‘quantity_sum’ => ‘xxx’,
    ]
);

what should i do?

Library should throw own exception types

It is a good practice for libraries to throw their own exception types instead of PHP/SPL types. Client applications may throw built-in exception types, but they will never throw third party library exceptions, so this practice avoids cases where trying to catch a particular type might catch the wrong exception.

Can I employ the 'use' language construct when using a string predicate?

Let's say I have something like this:

$foo = ['hello' => true];
$bar = ['hello' => 'candy canes'];

I can echo 'candy canes' like this:

foreach (Enumerable::from($foo)
            ->where('$v ==> $v')
            ->select(function ($v, $k) use ($bar) {return $bar[$k];}) as $baz) {
    echo $baz;
}

Is it possible to do something like this though?

foreach (Enumerable::from($foo)
            ->where('$v ==> $v')
            ->select('($v, $k) use ($bar) ==> $bar[$k]') as $baz) {
    echo $baz;
}

Obviously it throws an exception, I'm just wondering if it's possible.

Joining multiple arrays

Hello thank you for such awesome script!
I want to join 4 arrays. But honestly I coudn't undersand the documentation.
Right now I have an sql query:

$ZoneID = '1';
$TillageID = '2';
$rs = mySQLquery("SELECT
        CR.CropID AS CropID,
        CP.OperID AS OperID,
        CP.ParentOperID AS ParentOperID,
        A.ActionID AS ActionID,
        A.WorkloadUnit AS WorkloadUnit,
        A.WorkpayUnit AS WorkpayUnit,
        AT.ActionTypeID AS ActionTypeID,
        A.Labor_prod AS LaborProd,
        A.Labor_rate AS LaborRate,
        A.Mech_rate AS ServiceRate,
        AT.Category AS WorkCategory,
        CP.Feature AS Feature,
        CP.StartYear AS StartYear,
        CP.StartMonth AS StartMonth,
        CP.StartDay AS StartDay,
        CP.EndYear AS EndYear,
        CP.EndMonth AS EndMonth,
        CP.EndDay AS EndDay
        FROM
        ((mlp_cropplan CP
        INNER JOIN mlp_crops CR ON CP.CropID = CR.CropID)
        INNER JOIN mlp_actions A ON CP.ActionID = A.ActionID)
        INNER JOIN mlp_actiontypes AT ON A.ActionTypeID = AT.ActionTypeID
        WHERE (CP.TillageID = 0 OR CP.TillageID = " . $TillageID . ")
        AND (CP.ZoneID = 0 OR CP.ZoneID = " . $ZoneID . ")          
        ORDER BY CR.CropID ASC, CP.OperID ASC");

But I want to use yalinqo instead of mysql. I dumped all the date from these table and made php arrays. Here is the code:

$rs2 = from( $mlp_cropplan )
        ->where(function( $mlp_cropplan ) { 
            global $TillageID, $ZoneID;
            return ( ( $mlp_cropplan['TillageID'] == 0 || $mlp_cropplan['TillageID'] == $TillageID ) && ( $mlp_cropplan['ZoneID'] == 0 || $mlp_cropplan['ZoneID'] == $ZoneID ) ); 
        } )
        ->orderBy( function( $mlp_cropplan ) { return $mlp_cropplan['CropID']; } )
        ->thenBy( function( $mlp_cropplan ) { return $mlp_cropplan['CropID']; } )
        ->join( from( $mlp_crops ), 
            function( $mlp_cropplan ) { return $mlp_cropplan['CropID']; }, 
            function( $mlp_crops ) { return $mlp_crops['CropID']; }, 
            function( $mlp_cropplan, $mlp_crops ) {
                return array(
                    'CropID' => $mlp_cropplan['CropID'],
                    'OperID' => $mlp_cropplan['OperID'],
                    'ParentOperID' => $mlp_cropplan['ParentOperID'],
                    'Feature' => $mlp_cropplan['Feature'],
                    'StartYear' => $mlp_cropplan['StartYear'],
                    'StartMonth' => $mlp_cropplan['StartMonth'],
                    'StartDay' => $mlp_cropplan['StartDay'],
                    'EndYear' => $mlp_cropplan['EndYear'],
                    'EndMonth' => $mlp_cropplan['EndMonth'],
                    'EndDay' => $mlp_cropplan['EndDay'],
                    'ActionID' => $mlp_cropplan['ActionID'],
                );
            } )
        ->join( from( $mlp_actions ), 
            function( $mlp_cropplan ) { return $mlp_cropplan['ActionID']; }, 
            function( $mlp_actions ) { return $mlp_actions['ActionID']; }, 
            function( $mlp_cropplan, $mlp_actions ) {
                return array(
                    'CropID' => $mlp_cropplan['CropID'],
                    'OperID' => $mlp_cropplan['OperID'],
                    'ParentOperID' => $mlp_cropplan['ParentOperID'],
                    'ActionID' => $mlp_cropplan['ActionID'],
                    'WorkloadUnit' => $mlp_actions['WorkloadUnit'],
                    'WorkpayUnit' => $mlp_actions['WorkpayUnit'],
                    'LaborProd' => $mlp_actions['Labor_prod'],
                    'LaborRate' => $mlp_actions['Labor_rate'],
                    'ServiceRate' => $mlp_actions['Mech_rate'],
                    'Feature' => $mlp_cropplan['Feature'],
                    'StartYear' => $mlp_cropplan['StartYear'],
                    'StartMonth' => $mlp_cropplan['StartMonth'],
                    'StartDay' => $mlp_cropplan['StartDay'],
                    'EndYear' => $mlp_cropplan['EndYear'],
                    'EndMonth' => $mlp_cropplan['EndMonth'],
                    'EndDay' => $mlp_cropplan['EndDay'],
                    'ActionTypeID' => $mlp_actions['ActionTypeID'],  
                );
            } )
        ->join( from( $mlp_actiontypes ), 
            function( $mlp_cropplan ) { return $mlp_cropplan['ActionTypeID']; }, 
            function( $mlp_actiontypes ) { return $mlp_actiontypes['ActionTypeID']; }, 
            function( $mlp_cropplan, $mlp_actiontypes ) {
                return array(
                    'CropID' => $mlp_cropplan['CropID'],
                    'OperID' => $mlp_cropplan['OperID'],
                    'ParentOperID' => $mlp_cropplan['ParentOperID'],
                    'ActionID' => $mlp_cropplan['ActionID'],
                    'WorkloadUnit' => $mlp_cropplan['WorkloadUnit'],
                    'WorkpayUnit' => $mlp_cropplan['WorkpayUnit'],
                    'ActionTypeID' => $mlp_actiontypes['ActionTypeID'],
                    'LaborProd' => $mlp_cropplan['Labor_prod'],
                    'LaborRate' => $mlp_cropplan['Labor_rate'],
                    'ServiceRate' => $mlp_cropplan['Mech_rate'],
                    'WorkCategory' => $mlp_actiontypes['Category'],
                    'Feature' => $mlp_cropplan['Feature'],
                    'StartYear' => $mlp_cropplan['StartYear'],
                    'StartMonth' => $mlp_cropplan['StartMonth'],
                    'StartDay' => $mlp_cropplan['StartDay'],
                    'EndYear' => $mlp_cropplan['EndYear'],
                    'EndMonth' => $mlp_cropplan['EndMonth'],
                    'EndDay' => $mlp_cropplan['EndDay'],
                );
            } );

The code is working, bu after second join the data of the first join is disappearing, please help me :-(

Distinct exception cases should have distinct exception types

single() currently throws UnexpectedValueException for two distinct cases:

  1. The case where there are no matches, as well as
  2. the case where there are too many matches.

It is still possible to distinguish these exception cases by exception message, but it is preferable to catch different types rather than inspect the message because messages are subject to change and type comparison is faster, more succinct to write and clearer.

Remove autoload files

Currently I have a PHP application that I do not want to autoload Linq.php for everything, but your composer.json specifies autoload files which forced the inclusion of Linq.php for everything even when nothing is used from your library.

"autoload": {
        "psr-4": {
            "YaLinqo\\": "YaLinqo/"
        },
        "files": [
            "YaLinqo/Linq.php"
        ]
    },

I would suggest removing the files section and allow people to use the function "from" within your YaLinqo namespace.

// aliasing a function (PHP 5.6+)
use function YaLinqo\from as from;

This will also allow us to alias the from method so that we can call it something else. Maybe I want to do something like this.

// aliasing a function (PHP 5.6+)
use function YaLinqo\from as yfrom;

This could be helpful if I already have a function defined as "from".

'Cannot traverse an already closed generator' when running benchmarks from YaLinqoPerf

After playing around with YaLinqoPerf, I ran composer update to get the latest versions of the libraries and YaLinqo began to throw exceptions 'Cannot traverse an already closed generator' on some of the benchmarks.

Here is some sample output:

Iterating over 100 ints .....
-----------------------
  PHP     [for]               0.00001 sec   x1.0 (100%)
  PHP     [array functions]   0.00002 sec   x2.0 (+100%)
  YaLinqo                     0.00003 sec   x3.0 (+200%)
  Ginq                        0.00021 sec   x21.0 (+2000%)
  Pinq                        0.00016 sec   x16.0 (+1500%)

Generating array of 100 integers .....
--------------------------------
  PHP     [for]               0.00003 sec   x1.0 (100%)
  PHP     [array functions]   0.00003 sec   x1.0 (+0%)
  YaLinqo                     0.00007 sec   x2.3 (+133%)
  Ginq                        0.00022 sec   x7.3 (+633%)
  Pinq                        0.00008 sec   x2.7 (+167%)

Generating lookup of 100 floats, calculate sum .....
----------------------------------------------
  PHP                         0.00031 sec   x1.0 (100%)
  YaLinqo                     0.00086 sec   x2.8 (+177%)
  YaLinqo [string lambda]     0.00078 sec   x2.5 (+152%)
  Ginq                        0.00558 sec   x18.0 (+1701%)
  Pinq                        * Not implemented

Counting values in arrays ......
-------------------------
  PHP     [for]               0.00003 sec   x1.0 (100%)
  PHP     [array functions]   0.00007 sec   x2.3 (+133%)
  YaLinqo                     0.00010 sec   x3.3 (+233%)
  YaLinqo [string lambda]     0.00010 sec   x3.3 (+233%)
  Ginq                        0.00021 sec   x7.0 (+600%)
  Pinq                        0.00035 sec   x11.7 (+1067%)

Counting values in arrays deep .....
------------------------------
  PHP     [for]               0.00007 sec   x1.0 (100%)
  PHP     [array functions]   0.00051 sec   x7.3 (+629%)
  YaLinqo                     0.00092 sec   x13.1 (+1214%)
  Ginq                        0.00173 sec   x24.7 (+2371%)
  Pinq                        0.00442 sec   x63.1 (+6214%)

Filtering values in arrays ......
--------------------------
  PHP     [for]               0.00004 sec   x1.0 (100%)
  PHP     [array functions]   0.00008 sec   x2.0 (+100%)
  YaLinqo                     * Cannot traverse an already closed generator
  YaLinqo [string lambda]     * Cannot traverse an already closed generator
  Ginq                        0.00036 sec   x9.0 (+800%)
  Pinq                        0.00032 sec   x8.0 (+700%)

Filtering values in arrays deep ......
-------------------------------
  PHP     [for]               0.00039 sec   x1.0 (100%)
  PHP     [array functions]   0.00069 sec   x1.8 (+77%)
  YaLinqo                     * Cannot traverse an already closed generator
  YaLinqo [string lambda]     * Cannot traverse an already closed generator
  Ginq                        0.00428 sec   x11.0 (+997%)
  Pinq                        0.00529 sec   x13.6 (+1256%)

Sorting arrays ......
--------------
  PHP                         0.00002 sec   x1.0 (100%)
  YaLinqo                     0.00008 sec   x4.0 (+300%)
  YaLinqo [string lambda]     0.00007 sec   x3.5 (+250%)
  Ginq                        0.00023 sec   x11.5 (+1050%)
  Ginq    [property path]     0.00068 sec   x34.0 (+3300%)
  Pinq                        0.00023 sec   x11.5 (+1050%)

Joining arrays ......
--------------
  PHP                         0.00002 sec   x1.0 (100%)
  YaLinqo                     * Cannot traverse an already closed generator
  YaLinqo [string lambda]     * Cannot traverse an already closed generator
  Ginq                        0.00016 sec   x8.0 (+700%)
  Ginq    [property path]     0.00029 sec   x14.5 (+1349%)
  Pinq                        0.00109 sec   x54.5 (+5348%)

Aggregating arrays .......
------------------
  PHP     [for]               0.00008 sec   x1.0 (100%)
  PHP     [array functions]   0.00024 sec   x3.0 (+200%)
  YaLinqo                     0.00027 sec   x3.4 (+238%)
  YaLinqo [string lambda]     0.00031 sec   x3.9 (+288%)
  Ginq                        0.00088 sec   x11.0 (+1000%)
  Ginq    [property path]     0.00507 sec   x63.4 (+6238%)
  Pinq                        0.00186 sec   x23.3 (+2225%)

Aggregating arrays custom .....
-------------------------
  PHP                         0.00001 sec   x1.0 (100%)
  YaLinqo                     0.00007 sec   x7.0 (+600%)
  YaLinqo [string lambda]     0.00008 sec   x8.0 (+700%)
  Ginq                        0.00007 sec   x7.0 (+600%)
  Pinq                        0.00054 sec   x54.0 (+5301%)

Process data from ReadMe example .....
--------------------------------
  PHP                         0.00060 sec   x1.0 (100%)
  YaLinqo                     * Cannot traverse an already closed generator
  YaLinqo [string lambda]     * Cannot traverse an already closed generator
  Ginq                        0.00780 sec   x13.0 (+1200%)
  Pinq                        0.00340 sec   x5.7 (+467%)

Array of arrays - firstOrDefault by reference?

I have an array of arrays.
Is it possible to get the inner arrays by reference?

Example:

$arrayOfArrays = [
    [1, 2, 3]
];
$innerArray = Enumerable::from($arrayOfArrays)
    ->where(function ($innerArray) { return true; }) // Some filter logic comes here
    ->firstOrDefault();

$innerArray[0] = 10;

echo $arrayOfArrays[0][0]; // It's 1, not 10

Thank you very much!

Memory consumption of create_function()

I have noticed a lot of memory leaks if using the short syntax like

from($array)->select("explode(', ', $v)")->toArray();

But it's ok with closures

from($array)->select(function($var) { return explode(', ', $var); })->toArray();

proceeding first loop at one runtime with a big amount of data will cause to overhead of memory.

Not sure if this bottleneck is reason of lib implementation, or PHP's create_function(), but if you suggest me, I'll write a test samples of this issue.

not PHP8 compatible -> obsolete function create_function

Hi developers,

current version is not PHP8 compatible because of the obsolete function create_function in utils.php line 154.

It should be replaced with something like this:

$fun = function($args) use ($code){ ... };

But I could not successfully hanlde the statements in $code :-(

Can someone fix it?

Thx very much.

Undefined foreach variable

I have the following code:

$modulos = from($result)->where(function($item){ return $item->Padre == 0; })->toList();
foreach($modulos as $m){
     $childs = from($result)->where(function($item){ return $item->Padre == $m->Id; })->toList();
     $m->Children = $childs;
}
return $modulos;

However variable $m undefined, something am I doing wrong? or am I missing something?

Update please, PHP 8.2+

Hi Athari. I'm not happy with OOP-direction PHP is going, but it is still here to stay, and they've got JiT too. Can you please update yalinqo to work without deprecated notices on php 8.2?
I can't imagine my life without yalinqo.

image

please also fix the killer-feature of '$v>2' instead of fn($v) => $v > 2

Returning array from query to XML data

after a consultation with linq I present a problem to return the object, which returns me is a structure that can not handle

$xml =  from($array)
    ->select('$s ==>$s["PricedItineraries"]["PricedItinerary"]')
    ->orderBy('$s ==> $s["AirItineraryPricingInfo"]["ItinTotalFare"]["TotalFare"]
        ["@attributes"]["Amount"]')
    ->thenBy('$s ==> $s["AirItinerary"]["OriginDestinationOptions"]
        ["OriginDestinationOption"]["FlightSegment"]
        ["TPA_Extensions"]["ValidateAirline"]');

return

object(YaLinqo\OrderedEnumerable)#2294 (6) {
  ["source":"YaLinqo\OrderedEnumerable":private]=>
  object(YaLinqo\Enumerable)#2292 (1) {
    ["getIterator":"YaLinqo\Enumerable":private]=>
    object(Closure)#2293 (2) {
      ["static"]=>
      array(3) {
        ["self"]=>
        object(YaLinqo\Enumerable)#2282 (1) {
          ["getIterator":"YaLinqo\Enumerable":private]=>
          object(Closure)#2283 (1) {
            ["static"]=>
            array(1) {
              ["it"]=>
              object(ArrayIterator)#2281 (1) {
                ["storage":"ArrayIterator":private]=>
                array(3) {

the problem is I can not iterate over the object

but if I put toArray() get an error with the index and returns null

OrderedEnum Not Convering to Array

I have a nested set of objects and sorting and filtering them works great with the library, but getting to convert to a list or array isn't working. Any ideas?

Version 3 doesn't exist

The documentation claims: Add to composer.json: "athari/yalinqo": "^3.0". However, version 3 does not exist.

  • The requested package athari/yalinqo ^3 exists as athari/yalinqo[dev-master, 2.x-dev, v1.0.0.0, v1.0.1.0, v1.0.1.1, v1.0.x-dev, v1.1.0.0, v1.1.1, v1.1.2, v2.0.0.0, v2.0.x-dev, v2.1.0.0, v2.2.0.0, v2.3.0.0, v2.3.1, v2.4.0, v2.4.1] but these are rejected by your constraint.

PHP 7.2 Deprecations: (unset) cast

As described on official PHP documentation, in the new version 7.2 the (unset) cast is deprecated and in the class Enumerable there is an explicit cast at line 88.
This thing generate an internal server error that crash all the application.
This is the stack trace of error:
PHP Deprecated: The (unset) cast is deprecated in www\vendor\athari\yalinqo\YaLinqo\Enumerable.php on line 88

Can you fix it?
Thank you

How to handle errors

What's the best way to handle errors when no results are returned by a previous filter?

Traversing query to XML

al realizar la consulta

$xmlsort1 =  from($xdocsort1)
            ->select('$s ==>$s["PricedItineraries"]["PricedItinerary"]')
            ->orderBy('$s ==> $s["AirItineraryPricingInfo"]["ItinTotalFare"]["TotalFare"]["@attributes"]["Amount"]')
            ->thenBy('$s ==> $s["AirItinerary"]["OriginDestinationOptions"]["OriginDestinationOption"]["FlightSegment"]["TPA_Extensions"]["ValidateAirline"]');

me retorna este codigo

object(YaLinqo\OrderedEnumerable)#6363 (6) {
  ["source":"YaLinqo\OrderedEnumerable":private]=>
  object(YaLinqo\Enumerable)#6361 (1) {
    ["getIterator":"YaLinqo\Enumerable":private]=>
    object(Closure)#6362 (2) {
      ["static"]=>
      array(3) {
        ["self"]=>
        object(YaLinqo\Enumerable)#6351 (1) {
          ["getIterator":"YaLinqo\Enumerable":private]=>
          object(Closure)#6352 (1) {
            ["static"]=>
            array(1) {
              ["it"]=>
              object(ArrayIterator)#6350 (1) {
                ["storage":"ArrayIterator":private]=>
                array(3) {
                  ["@attributes"]=>
                  array(6) {
                    ["Version"]=>
                    string(1) "1"
                    ["CorrelationID"]=>
                    string(23) "39299486144985245710041"
                    ["EchoToken"]=>
                    string(36) "806228ad-94d0-4984-92d4-fd3d586051dd"
                    ["SequenceNmbr"]=>
                    string(1) "1"
                    ["TimeStamp"]=>
                    string(0) ""
                    ["TransactionIdentifier"]=>
                    string(1) "8"
                  }
                  ["Success"]=>
                  array(0) {
                  }

como puedo iterar o manejar el objeto , no puedo recorrerlo no puedo hacer nada con el .

Google Translate:

data handling

when making the request

I will return this code

as I can iterate or handle the object, I can not traverse I can not do anything with it

Return type of YaLinqo\Enumerable::getIterator() should either be compatible

Getting following error on php 8.2
Package: "athari/yalinqo": "^2.5",

[message] => Return type of YaLinqo\Enumerable::getIterator() should either be compatible with IteratorAggregate::getIterator(): Traversable, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice [file] => /var/www/html/custom/vendor/athari/yalinqo/YaLinqo/Enumerable.php

Custom comparer in orderBy is ignored if key selector is cached

Using latest "composer require athari/yalinqo", v2.4.2

<?php

require 'vendor/autoload.php';

$qwe = [
    'key3' => 3,
    'key2' => 1,
    'key1' => 2
];

$asd =
    from($qwe)->
    orderBy(
        // #1
        function($v, $k) {
            return $k;
        },

        // #2
        // '$k',

        // #3
        // YaLinqo\Functions::$key,
    function($a, $b) {
        echo "in\n";
        return $b <=> $a;
    })->
    toArray();

var_dump($asd);

Hi Alexander. If I run code like shown, with key_selector#1, I can see "echo in\n" executed, like expected.
But If I run code with key_selector#2 or key_selector#3, I never see "echo in\n" executed, $comparer is never executed. Sorting still works, but not with my custom comparer, just by alphabet.

I've digged into the sources, and I've found vendor\athari\yalinqo\YaLinqo\OrderedEnumerable.php:127

trySortBySingleField:
  elseif ($this->keySelector === Functions::$key)
    elseif ($this->sortOrder == SORT_ASC) {
      ksort($array, $this->sortFlags);

If your code found current key selector function is the one from the cache, it never even tries to run provided custom comparer function.

I expect orderBy to always run comparer function if it is present.
Thank you.

ReadMe: update syntax, sensible intro for newbies, FAQ

Update ReadMe to a more sensible state:

  1. Get rid of obsolete string lambda garbage. Cast arrays to objects. Make the code pretty, not scary mess it is now.
  2. Explain basics like what from does, how to chain, how to iterate (come on man, you copypasted that on StackOverflow 10 times already). Literally anything is better than what ReadMe contains now.
  3. Add FAQ with common mistakes like trying to replace ORM with YaLinqo, multiple iterations over a sequence, comparisions etc. Check issues here and on SO.
  4. Links to SO maybe? That stupid "opinionated" question would be a good fit.

GroupBy Deep works for groupBy('$v["A"]', '$v["B"]') but crashes for groupBy('$v["A"]', '$v["B"]', '$v["C"]')

Hi!

Beautiful package, but I have probably an easy roadblock to solve since this morning, please let me explain my scenario, I am gathering the following array result (Role/Area/Permissions) from a Laravel Builder Query:

array
  0 => 
    array
      'RoleName' => string 'Root'
      'AreaName' => string 'Global'
      'PermissionName' => string 'Post'
  1 => 
    array (size=3)
      'RoleName' => string 'Root'
      'AreaName' => string 'Global'
      'PermissionName' => string 'Delete'
  3 => 
    array (size=3)
      'RoleName' => string 'Editor'
      'AreaName' => string 'Europe'
      'PermissionName' => string 'Index'
  4 => 
    array (size=3)
      'RoleName' => string 'Editor'
      'AreaName' => string 'Europe'
      'PermissionName' => string 'Post'

and I was wondering how to produce the following array result using your groupBy method:

Root
    Global
        Post
        Delete
        ...

...

Editor
    Europe
        Index
        Area
        ...

This what I am currently using right now:

        $roles = from($permissions)
            ->groupBy('$v["RoleName"]', '$v["AreaName"]', '$v["PermissionName"]')
            ->toArray();

Thanks in advance!

Two conditions within where clause

While I'm trying to iterate through the WP users table to check meta option where ID and meta_key are the where clause conditions used in the following code:

$db_usermeta = $wpdb->get_results('SELECT * FROM ' . $wpdb->usermeta );
foreach ($db_users as $key => $row) {
	  $usermeta = from($db_usermeta)
	  ->where(function($db_usermeta) {
      return $db_usermeta["user_id"] === $row->ID && 
	  $db_usermeta["meta_key"] === "co_dateofbirth" ;})
	  ->toString();
	 echo 'co_dateofbirth value is : ' . $usermeta . '<br/>';
}

Can't install 2.5.0 together with PHPUnit 9.x

This conflict was added to composer.json in version 2.5.0:

    "conflict": {
        "phpunit/php-timer": ">=2"
    }

I am assuming this is because this projects depends on an old version of PHPUnit in order to maintain compatibility with old PHP versions. However, this conflict also applies when used as dependency in my project:

$ composer why-not athari/yalinqo 2.5
athari/yalinqo v2.5.0 conflicts phpunit/php-timer (>=2) 

Unfortunately, there is no conflict-dev setting. Maybe the conflict can be solved in a different way, perhaps by making a specific version of php-timer a direct dev-dependency?

Meta: add new methods

Ideas for new methods to add and example implementations in other libraries.

linq.js

  • must: Zip, Concat, Insert, Let, Memoize, MemoizeAll, BufferWithCount, SequenceEqual, Reverse
  • high: CascadeBreadthFirst, CascadeDepthFirst, Flatten, Scan, PreScan, Alternate, DefaultIfEmpty, Shuffle
  • maybe: Pairwise, PartitionBy, TakeExceptLast, TakeFromLast, Share

Ix

  • Defer, Case, DoWhile, If, IsEmpty, (Skip|Take)Last, StartWith, While

MoreLinq

  • Batch(Chunk?), Pad, (Skip|Take)Until, (Skip|Take)Every, Zip(Shortest|Longest)

EvenMoreLinq

  • Permutations, Subsets, PermutedSubsets, Random, RandomSubset, Slice

LinqLib

  • Permutations, Combinations, Statistical

PHP

  • Iterators: Recursive*Iterator
  • arrays: combine, flip, merge[_recursive], rand, replace[_recursive], walk_recursive, extract

other

  • toTable, toCsv, toExcelCsv

P.S. If you need any of these methods or have any other ideas for new features, please let me know. New features aren't high priority until someone actually needs them.

Iterating through two arrays of objects with same ids

Hello, is it possible to iterate through this two arrays of objects using the library?, and how do I get the $obj->id property so I can check using it inside the ->where() and retrieve an array with the objects where the id's are equal.
It would be great if you can provide an example.

//json_encode($arr) output:
[{"id":0,"name":"","surname":""},{"id":1,"name":"","surname":""},{"id":2,"name":"","surname":""},{"id":3,"name":"","surname":""},{"id":4,"name":"","surname":""}]
//json_encode($arr1) output:
[{"id":1,"name":"","surname":""},{"id":2,"name":"","surname":""},{"id":3,"name":"","surname":""},{"id":4,"name":"","surname":""},{"id":5,"name":"","surname":""}]

Thanks in advance!!!

There aren't enough examples & union method doesn't work as expected

The API is unusable if there aren't enough examples of the use of the methods. After many hours of trying to use the union() method, it doesn't generate the result expected in joining two simple arrays of strings because there are missing elements in the resulting array.

I don't know if i'm doing something wrong:

$local_types = ["MOBILE", "OFFICE", "WHATSAPP", "PRIVATE", "WORK", "MAIN"];
$remote_types = ["MOBILE", "RADIO", "WHATSAPP", "OFFICE"];

After executing:

Enumerable::from($local_types)->union($remote_types)->toArray();

The resulting array is:

"MOBILE",
"RADIO",
"WHATSAPP",
"PRIVATE",
"MAIN"

Where is the "OFFICE"?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.