Closed eebanos closed 5 years ago
@eebanos Do you want to concatenate arrays and remove items with duplicate ids? If not, please write plain old iterative code as I'm not sure I understand what you want exactly.
I can retrieve a new array of objects with the same 'id' with a simple nested foreach, but is it possible to iterate each object element for both arrays using the library?, something like:
$result = from($array)->each()
, can you provide an example.
Thanks
@eebanos I don't understand what you want to do with elements which are present in both arrays or in one array. Do you want to ignore one of values if ids are equal or process both of them? Do you want to somehow merge objects with same ids? Do you want to process elements which are present in only one array or do you want to skip them? What exactly do you want?
As mentioned before, given two arrays of objects, each object have a property called ID, I want to return a new array with all the objects that are present in both arrays, (matching IDs), it is very simple using a nested foreach, but using the library I can't 'enumerate' each object inside the array, can you provide one example??, I hope it is clearer this time, thank you for your patience.
@eebanos This is an intersection. The code would be something like:
// PHP 7.4 and newer
Enumerable::from($objects1)->intersect($objects2, fn($o) => $o->id)
// PHP 7.3 and older
Enumerable::from($objects1)->intersect($objects2, function ($o) { return $o->id; })
Note that this code will return an iterator with keys and values of the source array $objects1
preserved. You can iterate over it as is with foreach
; transform into an array with sequental indexes using toList
method etc. If you want to choose values from $objects2
over those in $objects1
(if it's important, for example, $objects2
is a list of updated values), then you can swap the array variables in the code.
$objectsIntersection = Enumerable::from($objects1)
->intersect($objects2, function ($o) { return $o->id; })
->toList();
Kudos, it works great!!!
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.Thanks in advance!!!