合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
~~~ /** * 对查询结果集进行排序 * @access public * @param array $list 查询结果 * @param string $field 排序的字段名 * @param array $sortby 排序类型 * asc正向排序 desc逆向排序 nat自然排序 * @return array */ function list_sort_by($list, $field, $sortby = 'asc') { if (is_array($list)) { $refer = $resultSet = array(); foreach ($list as $i => $data) { $refer[$i] = &$data[$field]; } switch ($sortby) { case 'asc': // 正向排序 asort($refer); break; case 'desc': // 逆向排序 arsort($refer); break; case 'nat': // 自然排序 natcasesort($refer); break; } foreach ($refer as $key => $val) { $resultSet[] = &$list[$key]; } return $resultSet; } return false; } ~~~ ~~~ //数组排序 private function arrayOrder($array, $vkey) { $newArr = array(); foreach ($array as $key => $v) { $newArr[$key][$vkey] = $v[$vkey]; } array_multisort($newArr, SORT_DESC, $array);//SORT_DESC为降序,SORT_ASC为升序 return $array; } ~~~ ***** ***** ***** 使用: ~~~ $data = []; $order = array('dir' => SORT_DESC, 'mtime' => SORT_DESC); multisort($data, $order); ~~~ ~~~ /** * 对数组进行多键值排序 * @param $array * @param $order */ public function multisort(&$array, $order) { usort($array, function ($a, $b) use ($order) { $sortMap = array('asc' => SORT_ASC, 'desc' => SORT_DESC); $aObj = (object)$a; $bObj = (object)$b; if (is_string($order)) { $order = array($order); } if (is_object($order)) { $order = (array)$order; } $i = 0; $cOrder = count($order); foreach ($order as $field => $dir) { if (is_numeric($field)) { $field = $dir; $dir = SORT_ASC; } // Goto next step when a mis-match is found. if ($aObj->$field != $bObj->$field) { break; } // All fields match return 0 if (++$i === $cOrder) { return 0; } } if ( ! is_numeric($dir)) { $dir = strtolower($dir); $dir = $sortMap[$dir]; } $d = ($dir === SORT_DESC) ? -1 : 1; $c = ($aObj->$field < $bObj->$field) ? -1 : 1; return $c * $d; }); } ~~~