/ Gists / lambda usort sorting
On gists

lambda usort sorting

PHP

sort.php Raw #

<?php
$x = [
	[
		'name' => 'BBB',
		'pts' => 30,
	],
	[
		'name' => 'AAA',
		'pts' => 90,
	],
	[
		'name' => 'CCC',
		'pts' => 40,
	]
];

usort($x, sortBy('pts', 'DESC')); // Změna zde - přidán parametr pro směr řazení

function sortBy($k, $sortOrder = 'ASC') // Změna zde - přidán druhý parametr s výchozí hodnotou ASC
{
	return function($a, $b) use ($k, $sortOrder)
	{
		$result = $a[$k] <=> $b[$k];
		return ($sortOrder === 'ASC') ? $result : -$result; // Změna zde - záporná hodnota pro DESC řazení
	};
}

echo "<pre>";
print_r($x);



//  2 way


function customSort($a, $b, $key, $sortOrder) {
    return $sortOrder === 'ASC' ? ($a[$key] <=> $b[$key]) : ($b[$key] <=> $a[$key]);
}

$key = 'name'; // Změňte podle sloupce, podle kterého chcete řadit
$sortOrder = 'ASC'; // Změňte na 'DESC' pro sestupné řazení

usort($x, function($a, $b) use ($key, $sortOrder) {
    return customSort($a, $b, $key, $sortOrder);
});

echo "<pre>";
print_r($x);

invoke.php Raw #

<?php

// 1
class Comparator
{
    private $key;

    public function __construct(string $key)
    {
        $this->key = $key;
    }

    public function __invoke($a, $b)
    {
        return $a[$this->key] <=> $b[$this->key];
    }
}

$customers = [
    ['id' => 1, 'name' => 'John', 'credit' => 20000],
    ['id' => 3, 'name' => 'Alice', 'credit' => 10000],
    ['id' => 2, 'name' => 'Bob', 'credit' => 15000]
];

// sort customers by names
usort($customers, new Comparator('name'));
print_r($customers);

// sort customers by credit
usort($customers, new Comparator('credit'));
print_r($customers);



// 2
function comparatorFn($key) {
	
	return function($a, $b) use ($key) {
		return $a[$key] <=> $b[$key];
	};
	
}

$customers = [
    ['id' => 1, 'name' => 'John', 'credit' => 20000],
    ['id' => 3, 'name' => 'Alice', 'credit' => 10000],
    ['id' => 2, 'name' => 'Bob', 'credit' => 15000]
];

echo "<pre>";

// sort customers by names
usort($customers, comparatorFn('name'));
print_r($customers);

// sort customers by credit
usort($customers, comparatorFn('credit'));
print_r($customers);