-
Notifications
You must be signed in to change notification settings - Fork 4
Common Patterns
Making a list of ids from an array of records is quite common. Here are two approaches.
$employeeIds = Sequence::make($employees) // make the array into a Sequence
->pluck('employeeId') // Extract the employee id
->to_a(); // Convert it into an arrayBehind the scenes, ->pluck('fieldName') is just an alias for:
->map(fn\fnPluck('fieldName'))
$employeeIds = Sequence::make($employees) // make the array into a Sequence
->map(fn\fnPluck('employeeId')) // Extract the employee id
->to_a(); // Convert it into an array$employeeIds = Sequence::make($employees) // make the array into a Sequence
->keyBy(fn\fnPluck('employeeId')) // Extract the employee id as assign it to the key
->to_a(); // Convert it into an arrayThe easiest way to get the keys from an array or iterator:
$keys = Sequence::make($peopleKeyedById) // make the array|iterator into a Sequence
->keys() // get the keys
->to_a();Using a Closure function (Note: ->map passes the key in as the second parameter):
$keys = Sequence::make($peopleKeyedById) // make the array|iterator into a Sequence
->map(function ($value, $key) { // write a Closure to extract $key
return $key;
})
->values() // Re-key starting with 0
->to_a();A more sophisticated way that shows some useful functions:
$keys = Sequence::make($peopleKeyedById)
->map(fn\fnSwapParamsPassThrough(fn\fnIdentity()))
->values()
->to_a();fnSwapParamsPassThrough will swap the $value and $key param and call fnIdentity.
fnIdentity returns the first parameter.
$fn = fn\fnIdentity();
$true = $fn(101) === 101;$employeesSortedById = Sequence::make($employees) // make the array into a Sequence
->sort(fn\fnCompareField('employeeId')) // sort the employees by their id
->to_a();$employeesSortedById = Sequence::make($employees) // make the array into a Sequence
->sort(fn\fnCompareFieldRev('employeeId')) // sort the employees by their id in reverse order
->to_a();The following example will first sort the list and then key by the employee id:
$employeesSortedById = Sequence::make($employees) // make the array into a Sequence
->sort(fn\fnCompareField('lastName')) // sort the employees by their last name
->keyBy(fn\fnPluck('employeeId')) // key by the employee id
->to_a();To sort and preserve the keys, use asort instead of sort:
$employeesSortedById = Sequence::make($employees) // make the array into a Sequence
->keyBy(fn\fnPluck('employeeId')) // key by the employee id
->asort(fn\fnCompareField('lastName')) // sort the employees by their last name
->to_a();Warning: sort does NOT preserve numeric keys, if you need to preserve the keys, use asort. The following will NOT be keyed by employeeId:
$employeesSortedById = Sequence::make($employees) // make the array into a Sequence
->keyBy(fn\fnPluck('employeeId')) // key by the employee id
->sort(fn\fnCompareField('lastName')) // **Keys are lost**
->to_a();