Home > php教程 > php手册 > 对查询结果集进行正向、逆向和自然排序

对查询结果集进行正向、逆向和自然排序

WBOY
Release: 2016-06-07 11:45:57
Original
1309 people have browsed it

该方法可以用于对ThinkPHP的查询数据集(模型类的select方法的返回值)进行动态排序,支持正向、逆向和自然排序。/**<br>  +----------------------------------------------------------<br>  * 对查询结果集进行排序<br>  +----------------------------------------------------------<br>  * @access public<br>  +----------------------------------------------------------<br>  * @param array $list 查询结果<br>  * @param string $field 排序的字段名<br>  * @param string $sortby 排序类型<br>  * asc正向排序 desc逆向排序 nat自然排序<br>  +----------------------------------------------------------<br>  * @return array<br>  +----------------------------------------------------------<br>  */<br> function list_sort_by($list,$field, $sortby='asc') {<br>    if(is_array($list)){<br>        $refer = $resultSet = array();<br>        foreach ($list as $i => $data)<br>            $refer[$i] = &$data[$field];<br>        switch ($sortby) {<br>            case 'asc': // 正向排序<br>                 asort($refer);<br>                 break;<br>            case 'desc':// 逆向排序<br>                 arsort($refer);<br>                 break;<br>            case 'nat': // 自然排序<br>                 natcasesort($refer);<br>                 break;<br>        }<br>        foreach ( $refer as $key=> $val)<br>            $resultSet[] = &$list[$key];<br>        return $resultSet;<br>    }<br>    return false;<br> }使用示例(下面的示例代码仅在ThinkPHP环境下面有效):$Blog = M('Blog');<br> $list = $Blog->limit(10)->select();<br> $list1 = list_sort_by($list,'status','desc'); // 对结果集按照status字段逆向排序<br> $list2 = list_sort_by($list,'cate_id','asc'); // 对结果集按照cate_id字段正向排序

AD:真正免费,域名+虚机+企业邮箱=0元

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template