note 119944 added to array.sorting

From: Date: Sat, 24 Sep 2016 22:55:59 +0000
Subject: note 119944 added to array.sorting
Groups: php.notes 
Request: Send a blank email to php-notes+get-206664@lists.php.net to get a copy of this message
Stabilizing the sort functions (in this case, usort). <?php function stable_usort(&$array, $cmp) { $i = 0; $array = array_map(function($elt)use(&$i) { return [$i++, $elt]; }, $array); usort($array, function($a, $b)use($cmp) { return $cmp($a[1], $b[1]) ?: ($a[0] - $b[0]); }); $array = array_column($array, 1); } ?> Tags each array element with its original position in the array so that when the comparison function returns 0 the tie can be broken to put the earlier element first. ---- Server IP: 202.78.240.39 Probable Submitter: 222.153.123.142 ---- Manual Page -- http://php.net/manual/en/array.sorting.php Edit -- https://master.php.net/note/edit/119944 Del: integrated -- https://master.php.net/note/delete/119944/integrated Del: useless -- https://master.php.net/note/delete/119944/useless Del: bad code -- https://master.php.net/note/delete/119944/bad+code Del: spam -- https://master.php.net/note/delete/119944/spam Del: non-english -- https://master.php.net/note/delete/119944/non-english Del: in docs -- https://master.php.net/note/delete/119944/in+docs Del: other reasons-- https://master.php.net/note/delete/119944 Reject -- https://master.php.net/note/reject/119944 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#206664) next »