PHP code example of tuck / sort
1. Go to this page and download the library: Download tuck/sort 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/ */
tuck / sort example snippets
use Tuck\Sort\Sort;
Sort::values(['foo', 'bar', 'baz']); // returns ['bar', 'baz', 'foo']
Sort::keys(['x' => 'foo', 'm' => 'bar']); // returns ['m' => 'bar', 'x' => 'foo']
Sort::natural(['img12.jpg', 'img2.jpg', 'img1.jpg']); // returns ['img1.jpg', 'img2.jpg', 'img12.jpg']
Sort::user(
[3, 2, 5, 6],
function () { /* custom sorting */ }
);
$results = $metrics->getTotals();
sort($results);
Sort::values($metrics->getTotals());
$x = [3, 1, 2];
var_dump(Sort::values($x)); // 1, 2, 3
var_dump($x); // 3, 1, 2
asort()
sort()
ksort()
natsort()
usort()
uasort()
uksort()
Sort::values()
Sort::keys()
Sort::natural()
Sort::user()
Sort::values([3 => 'bob', 1 => 'alice']);
// returns [0 => 'alice', 1 => 'bob']
Sort::values([3 => 'bob', 1 => 'alice'], Sort::PRESERVE_KEYS);
// returns [1 => 'alice', 3 => 'bob']
Sort::values(['foo', 'bar', 'baz'], Sort::PRESERVE_KEYS);
Sort::natural(['foo', 'bar', 'baz'], Sort::PRESERVE_KEYS);
Sort::user(
[3, 2, 5, 6],
function () { /* custom sorting */ },
Sort::PRESERVE_KEYS
);
$x = new ArrayIterator([3, 1, 2]);
Sort::values($x); // returns [1, 2, 3]
Sort::user($list, function (HighScore $a, HighScore $b) {
return $a->getPoints() <=> $b->getPoints();
});
Sort::by($list, function (HighScore $a) {
return $a->getPoints();
});
Sort::byDescending($list, function (HighScore $a) {
return $a->getPoints();
});
usort(
$unsorted,
function (HighScore $scoreA, HighScore $scoreB) {
$a = $scoreA->getPoints();
$b = $scoreA->getPoints();
if ($a == $b) {
$a = $scoreA->getDate();
$b = $scoreB->getDate();
}
if ($a == $b) {
$a = $scoreA->getName();
$b = $scoreB->getName();
}
return $a <=> $b;
}
);
Sort::chain()
->compare(function (HighScore $a, HighScore $b) {
return $a->getPoints() <=> $b->getPoints();
})
->compare(function (HighScore $a, HighScore $b) {
return $a->getDate() <=> $b->getDate();
})
->compare(function (HighScore $a, HighScore $b) {
return $a->getName() <=> $b->getName();
});
$sortChain = Sort::chain()
->desc(function (HighScore $score) {
return $score->getPoints();
})
->asc(function (HighScore $score) {
return $score->getDate();
})
->asc(function (HighScore $score) {
return $score->getName();
});
$sortChain->values(['foo', 'bar']);
$sortChain->values(['foo', 'bar'], Sort::PRESERVE_KEYS);
$sortChain->keys(['foo' => 'blah', 'bar' => 'blat']);
$sortChain('steven', 'connie'); // returns -1, 0 or 1
$yourCustomCollection->usort($sortChain);
$sortOrder = Sort::chain();
if ($options['sort_by_name']) {
$sortOrder->asc(...);
}
// etc
$a