Using a Static Class Method to *Quickly* Sort an Array By Key Value in PHP -
this question different others, it's focus on sorting array static class method rather typical procedural approach.
i performant way implement function sortbykeyvalue below. other related answers focused on getting job done, question more getting job done , getting done (as static method).
anyone want take crack @ it? i'll throw bounty on question squeeze out performance junkies. :)
<?php $data = array( array('name' => 'b', 'cheesy' => 'bacon'), array('name' => 'c', 'delicious' => 'tacos'), array('name' => 'a', 'lovely' => 'viddles'), ); class myarray { public static function sortbykeyvalue($array, $key, $direction = 'asc') { // thing // me! return $array; } } $data = myarray::sortbykeyvalue($data, 'name'); // should output name key in order // not including garbage keys threw in, should there too) // [{"name": "a"},{"name": "b"},{"name": "c"}] ?>
i ran following compare speed of multisort
, pre-php 5.3 method, more modern method uses usort
closure function:
$alpha = 'abcdefghijklmnopqrstuvwxyz'; $cnt = 1000; $key = 'name'; $direction = 'asc'; $array = array(); ($i=0; $i<$cnt; $i++){ $array[$i]['name'] = substr(str_shuffle($alpha), 0, 8); $array[$i]['job'] = substr(str_shuffle($alpha), 0, 8); } $pre = $array;//the test dummies //pre-php 5.3 $t[0] = -microtime(); $sub = array(); foreach ($pre $item) { $sub[] = $item[$key]; } if ($direction == 'asc') $ord = sort_asc; else $ord = sord_desc; array_multisort($sub, $ord, $pre); $t[0] += microtime(); //usort closure $t[1] = -microtime(); usort($array, function ($a, $b) use($key, $direction){ if ($direction == 'asc'){ return strcmp($a[$key], $b[$key]); } return strcmp($b[$key], $a[$key]); }); $t[1] += microtime(); var_dump($t);
as can see, old method more twice fast:
array ( [0] => 0.005 [1] => 0.014001 )
so here's how class:
class myarray { public static function sortbykeyvalue($array, $key, $direction = sort_asc) { $sub = array(); foreach ($array $item) { $sub[] = $item[$key]; } array_multisort($sub, $direction, $array); return $array; } }
Comments
Post a Comment