某个字段排序
/** * 对二维数组进行排序(某个字段) * 模拟 数据表记录按字段排序 * * <code> * @list_order($list, $get['orderKey'], $get['orderType']); * </code> * @param array $array 要排序的数组 * @param string $orderKey 排序关键字/字段 * @param string $orderType 排序方式,'asc':升序,'desc':降序 * @param string $orderValueType 排序字段值类型,'number':数字,'string':字符串 * @link /article/1000.html */ function list_order(&$array, $orderKey, $orderType = 'asc', $orderValueType = 'string') { if ($array && is_array($array)) { $orderArr = array(); foreach ($array as $val) { $orderArr[] = $val[$orderKey]; } $orderType = ($orderType == 'asc') ? SORT_ASC : SORT_DESC; $orderValueType = ($orderValueType == 'string') ? SORT_STRING : SORT_NUMERIC; array_multisort($orderArr, $orderType, $orderValueType, $array); } }
应用:
@list_order($list, $get['orderKey'], $get['orderType'], "string");
多字段排序
/** * 对二维数组进行多字段排序 * * @param array $list 排序数组 * @param array $order_fields 字段排序规则 $list = list_order_by_cols($list, array( 'parent' => SORT_ASC, 'value' => SORT_DESC, )); * @return array * @link /article/643.html */ function list_order_by_cols($list, $order_fields) { if (empty($list)) { return []; } if (empty($order_fields)) { return $list; } $sort_arr = []; $sort_rule = ''; foreach ($order_fields as $sort_field => $sort_way) { foreach ($list as $key => $val) { $sort_arr[$sort_field][$key] = $val[$sort_field]; } $sort_rule .= '$sort_arr["' . $sort_field . '"],' . $sort_way . ','; } if (empty($sort_arr) || empty($sort_rule)) { return $list; } eval('array_multisort(' . $sort_rule . ' $list);'); return $list; }
二维数组分页
/** * 二维数组分页(1) * * @param array $array 分页数组 * @param int $cur_page 当前分页数 * @param int $page_size 每页记录数 * @param array $order_fields 字段排序规则 * @return array */ function list_page(&$list = [], $cur_page = 1, $page_size = 20, $order_fields = array()) { if (empty($list) || !is_array($list)) { return []; } // 排序 $list = list_order_by_cols($list, $order_fields); // 分页 return array_slice($list, $page_size * ($cur_page - 1), $page_size); } /** * 二维数组分页(2) * * @param array $list 待分页数组 * @param int $cur_page 当前分页数 * @param int $page_size 每页记录数 * @param array $order_fields 字段排序规则 * @return array */ function list_page_info(&$list = array(), $cur_page = 1, $page_size = 20, $order_fields = array()) { if (!is_array($list) || empty($list)) { return array( 'page' => 0, 'total_page' => 0, 'list' => array() ); } // 排序 $list = list_order_by_cols($list, $order_fields); $page_size = trim($page_size); $page_size = empty($page_size) ? 20 : intval($page_size); $total_page = ceil(count($list) / $page_size); $cur_page = max(1, $cur_page); $cur_page = min($cur_page, $total_page); // 分页 return array( 'page' => intval($cur_page), 'total_page' => $total_page, 'list' => array_slice($list, $page_size * ($cur_page - 1), $page_size) ); }
相关文章: