note 123923 added to function.usort

From: Date: Mon, 10 Jun 2019 13:23:06 +0000
Subject: note 123923 added to function.usort
Groups: php.notes 
Request: Send a blank email to php-notes+get-211204@lists.php.net to get a copy of this message
This is a simple way to sort based on a "priority list": <?php $order = [1,3,0,2]; $arr = [ [ 'id' => 0 ], [ 'id' => 1 ], [ 'id' => 2 ], [ 'id' => 3 ], ]; uasort( $arr, function ($a, $b) use ($order) { return array_search($a['id'], $order) <=> array_search($b['id'], $order); } ); print_r($arr); ?> This will return: Array ( [1] => Array ( [id] => 1 ) [3] => Array ( [id] => 3 ) [0] => Array ( [id] => 0 ) [2] => Array ( [id] => 2 ) ) Note that if you have a value in $arr that is not on the $order list, you will need additional checks since the array_search function returns FALSE for undefined indexes. ---- Server IP: 208.43.231.9 Probable Submitter: 185.85.3.134 (proxied: 2001:1284:f01c:64df:e124:a41e:361f:6014) ---- Manual Page -- http://php.net/manual/en/function.usort.php Edit -- https://master.php.net/note/edit/123923 Del: integrated -- https://master.php.net/note/delete/123923/integrated Del: useless -- https://master.php.net/note/delete/123923/useless Del: bad code -- https://master.php.net/note/delete/123923/bad+code Del: spam -- https://master.php.net/note/delete/123923/spam Del: non-english -- https://master.php.net/note/delete/123923/non-english Del: in docs -- https://master.php.net/note/delete/123923/in+docs Del: other reasons-- https://master.php.net/note/delete/123923 Reject -- https://master.php.net/note/reject/123923 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#211204) next »