PHP code example of artoodetoo / recordset
1. Go to this page and download the library: Download artoodetoo/recordset 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/ */
artoodetoo / recordset example snippets
use R2\Helpers\ArrayRecordset;
$records = [
['name' => 'Alfred', 'age' => 40],
['name' => 'Mark', 'age' => 40],
['name' => 'Lue', 'age' => 45],
['name' => 'Ameli', 'age' => 38],
['name' => 'Barb', 'age' => 38],
];
$result = (new ArrayRecordset($records))
->orderBy('age', 'desc')
->orderBy('name', 'asc')
->get();
// will be equal to
// [
// ['name' => 'Lue', 'age' => 45],
// ['name' => 'Alfred', 'age' => 40],
// ['name' => 'Mark', 'age' => 40],
// ['name' => 'Ameli', 'age' => 38],
// ['name' => 'Barb', 'age' => 38],
// ];
$result = (new ArrayRecordset($records))
->pluck('name);
// will be equal to
// ['Alfred', 'Mark', 'Lue', 'Ameli', 'Barb']
$result = (new ArrayRecordset($records))
->pluck('age', 'name);
// will be equal to
// ['Alfred' => 40, 'Mark' => 40, 'Lue' => 45, 'Ameli' => 38, 'Barb' => 38]
$result = (new ArrayRecordset($this->nameAge))
->groupBy('age')
->get();
// will be equal to
// [
// 38 => [
// ['name' => 'Ameli', 'age' => 38],
// ['name' => 'Barb', 'age' => 38],
// ],
// 40 => [
// ['name' => 'Alfred', 'age' => 40],
// ['name' => 'Mark', 'age' => 40],
// ],
// 45 => [
// ['name' => 'Lue', 'age' => 45],
// ],
// ]
$comparator = function ($a, $b) {
return strlen($a['name']) - strlen($b['name']);
};
$result = (new ArrayRecordset($record))
->orderBy('age')
->orderByCallable($comparator)
->get();
// will be equal to
// [
// ['name' => 'Barb', 'age' => 38],
// ['name' => 'Ameli', 'age' => 38],
//
// ['name' => 'Mark', 'age' => 40],
// ['name' => 'Alfred', 'age' => 40],
//
// ['name' => 'Lue', 'age' => 45],
// ]
ArrayRecordset::macro(
'orderByKeepOnTop',
function (string $field, string $onTop, string $direction = 'asc') {
$sign = strtolower($direction) === 'asc' ? 1 : -1;
$this->comparators[] = function ($a, $b) use ($field, $onTop, $sign) {
$r = ($b[$field] == $onTop) <=> ($a[$field] == $onTop);
return $r == 0 ? strnatcasecmp($a[$field], $b[$field]) * $sign : $r;
};
return $this;
}
);
// Whenever you sort by ascending or descending order,
// Barb will be on top of the list!
$result = (new ArrayRecordset($this->nameAge))
->orderByKeepOnTop('name', 'Barb', 'asc')
->get();
// will be equal to
// [
// ['name' => 'Barb', 'age' => 38],
// ['name' => 'Alfred', 'age' => 40],
// ['name' => 'Ameli', 'age' => 38],
// ['name' => 'Lue', 'age' => 45],
// ['name' => 'Mark', 'age' => 40],
// ]