array_sort.php function array_sort($array,$sortRule="",$order="asc"){ /** * $array = [ * ["book"=10,"version"=10], * ["book"=19,"version"=30], * ["book"=10,"version"=30], * ["book"=19,"version"=10], * ["book"=10,"version"=20], * ["book"=19,
function array_sort($array,$sortRule="",$order="asc"){ /** * $array = [ * ["book"=>10,"version"=>10], * ["book"=>19,"version"=>30], * ["book"=>10,"version"=>30], * ["book"=>19,"version"=>10], * ["book"=>10,"version"=>20], * ["book"=>19,"version"=>20] * ]; */ if(is_array($sortRule)){ /** * $sortRule = ['book'=>"asc",'version'=>"asc"]; */ usort($array, function ($a, $b) use ($sortRule) { foreach($sortRule as $sortKey => $order){ if($a[$sortKey] == $b[$sortKey]){continue;} return (($order == 'desc')?-1:1) * (($a[$sortKey] < $b[$sortKey]) ? -1 : 1); } return 0; }); }else if(is_string($sortRule) && !empty($sortRule)){ /** * $sortRule = "book"; * $order = "asc"; */ usort($array,function ($a,$b) use ($sortRule,$order){ if($a[$sortRule] == $b[$sortRule]){ return 0; } return (($order == 'desc')?-1:1) * (($a[$sortRule] < $b[$sortRule]) ? -1 : 1); }); }else{ usort($array,function ($a,$b) use ($order){ if($a== $b){ return 0; } return (($order == 'desc')?-1:1) * (($a < $b) ? -1 : 1); }); } return $array; }