| 1 |
<?php |
| 2 |
/** |
| 3 |
* Copyright (C) 2019-2023 Graham Breach |
| 4 |
* |
| 5 |
* This program is free software: you can redistribute it and/or modify |
| 6 |
* it under the terms of the GNU Lesser General Public License as published by |
| 7 |
* the Free Software Foundation, either version 3 of the License, or |
| 8 |
* (at your option) any later version. |
| 9 |
* |
| 10 |
* This program is distributed in the hope that it will be useful, |
| 11 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 |
* GNU Lesser General Public License for more details. |
| 14 |
* |
| 15 |
* You should have received a copy of the GNU Lesser General Public License |
| 16 |
* along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 |
*/ |
| 18 |
/** |
| 19 |
* For more information, please contact <graham@goat1000.com> |
| 20 |
*/ |
| 21 |
|
| 22 |
namespace Goat1000\SVGGraph; |
| 23 |
|
| 24 |
/** |
| 25 |
* Class for sorting array by field |
| 26 |
*/ |
| 27 |
class FieldSort { |
| 28 |
|
| 29 |
private $key = null; |
| 30 |
private $reverse = false; |
| 31 |
|
| 32 |
public function __construct($key, $reverse = false) |
| 33 |
{ |
| 34 |
$this->key = $key; |
| 35 |
$this->reverse = $reverse; |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Sorts the array based on value of key field |
| 40 |
*/ |
| 41 |
public function sort(&$data) |
| 42 |
{ |
| 43 |
$key = $this->key; |
| 44 |
$get_val = function($a, $key) { |
| 45 |
return (!isset($a[$key]) || $a[$key] === null ? PHP_INT_MIN : $a[$key]); |
| 46 |
}; |
| 47 |
$bigger = function($a, $b, $key) use($get_val) { |
| 48 |
$va = $get_val($a, $key); |
| 49 |
$vb = $get_val($b, $key); |
| 50 |
if($va == $vb) |
| 51 |
return 0; |
| 52 |
return $va > $vb ? 1 : -1; |
| 53 |
}; |
| 54 |
$smaller = function($a, $b, $key) use($get_val) { |
| 55 |
$va = $get_val($a, $key); |
| 56 |
$vb = $get_val($b, $key); |
| 57 |
if($va == $vb) |
| 58 |
return 0; |
| 59 |
return $va < $vb ? 1 : -1; |
| 60 |
}; |
| 61 |
$fn = $this->reverse ? $smaller : $bigger; |
| 62 |
usort($data, function($a, $b) use($key, $fn) { |
| 63 |
return $fn($a, $b, $key); |
| 64 |
}); |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
|