Comment organiser efficacement un tableau multidimensionnel basé sur une colonne spécifiée, notamment lorsque les données comportent des dates et que vous désirez des critères de tri personnalisés ?
Présentation d'une solution améliorée pour PHP 5.3
Cette solution offre plusieurs avantages :
function make_comparer() { // Normalize criteria $criteria = func_get_args(); foreach ($criteria as $index => $criterion) { $criteria[$index] = is_array($criterion) ? array_pad($criterion, 3, null) : array($criterion, SORT_ASC, null); } return function ($first, $second) use (&$criteria) { foreach ($criteria as $criterion) { // Comparison details list($column, $sortOrder, $projection) = $criterion; $sortOrder = $sortOrder === SORT_DESC ? -1 : 1; // Project and compare values $lhs = $projection ? call_user_func($projection, $first[$column]) : $first[$column]; $rhs = $projection ? call_user_func($projection, $second[$column]) : $second[$column]; // Determine the comparison result if ($lhs < $rhs) { return -1 * $sortOrder; } elseif ($lhs > $rhs) { return 1 * $sortOrder; } } // Tiebreakers exhausted return 0; }; }
Considérez l'échantillon data :
$data = array( array('zz', 'name' => 'Jack', 'number' => 22, 'birthday' => '12/03/1980'), array('xx', 'name' => 'Adam', 'number' => 16, 'birthday' => '01/12/1979'), array('aa', 'name' => 'Paul', 'number' => 16, 'birthday' => '03/11/1987'), array('cc', 'name' => 'Helen', 'number' => 44, 'birthday' => '24/06/1967'), );
Tri de base :
Tri avec plusieurs Colonnes :
Fonctionnalités avancées :
Cas d'utilisation complexe :
Trier par la colonne "numéro" décroissant, suivi du colonne "anniversaire" projetée par ordre croissant :
usort($data, make_comparer( ['number', SORT_DESC], ['birthday', SORT_ASC, 'date_create'] ));
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!