PHP数组分组排序程序代码
php中数据排序可以用sort但如果要做到数组分组排序的话我们可以使用ar(www.phpfensi.com)ray_multisort函数或者使用多重复遍历来做,下面看一个例子.
PHP的数组,数组中的内容大致如下:
- $list = array(
- array(2,3,5),
- array(2,5,24),
- array(3,8,6),
- array(3,2,10),
- array(4,7,20),
- array(4,1,15),
- array(6,4,10),
- array(7,9,20),
- );
为了方便表达,我把3列数字分别称为,ABC三列.
需求:默认以A列排序为主,如果A列相同则以C列倒序排列相同的元素,B列其实没有参与排序,但是在实际运用中有用,所以我也写出来了.
方法一,代码如下:
- $a = $c = array();
- foreach($list as $val){
- $a[] = $val[0]; //a列
- $c[] = $val[2]; //c列
- }
- //安装a列升序,然后安装b列降序 , 类似sql,orderby a asc,b desc
- array_multisort($a,SORT_ASC , $c, SORT_DESC, $list);
- print_r($list);
方法二,代码如下:
- for($j=0;$j<count($list);$j++) {
- for($i=count($list)-1;$i>$j;$i--){
- if($list[$i][0] == $list[$i-1][0] && $list[$i][2] > $list[$i-1][2])
- list($list[$i],$list[$i-1]) = array($list[$i-1],$list[$i]);
- }
- }
例子2,例如有下面的数据,从数据库里查出来的,是一个二维数组.
- [0] => Array ( [trans_lang_id] => 1 [country_id] => 1 [trans_origin_id] => 1 [page_id] => 1 [trans_content] => test1
- [1] => Array ( [trans_lang_id] => 2 [country_id] => 1 [trans_origin_id] => 2 [page_id] => 1 [trans_content] => test2
- [2] => Array ( [trans_lang_id] => 3 [country_id] => 1 [trans_origin_id] => 3 [page_id] => 1 [trans_content] => test3
- [3] => Array ( [trans_lang_id] => 4 [country_id] => 1 [trans_origin_id] => 4 [page_id] => 1 [trans_content] => test4
- [4] => Array ( [trans_lang_id] => 6 [country_id] => 2 (www.phpfensi.com)[trans_origin_id] => 1 [page_id] => 2 [trans_content] => test5
怎样按照country_id 和page_id分组,将里面的数据查分成多个数组?
也就是country_id和page_id相同的数据成为一个新数组,因为这样的数据会输出到同一个csv文件,比如文件名为 zh_CN_1.csv,代码如下:
- Array Translates:
- US_en:Array (
- [1] => Array (
- [0] => Array ( [0] => test [1] => 测试)
- [1] => Array ( [0] => test [1] => 测试)
- [2] => Array ( [0] => test [1] => 测试)
- [3] => Array ( [0] => test [1] => 测试 )
- )
- )
- CN_zh:Array (
- [2] => Array (
- [0] => Array ( [0] => There are no user contributed notes for this page. [1] => this belong to another country )
- )
- )
- foreach ($translates as $translate) {
- $data[$translate["language_code"] . "_" . $translate['short_name'] ][$translate['page_id']][] = array($translate['content'], $translate['trans_content']);
- }
- foreach ($data as $locale_key => $item) {
- foreach ($item as $page_key => $csvContent) {
- $fileName = $locale_key . "_" . $page_key . ".csv";
- $translationFile->generateCSV($fileName, $csvContent);
- }
这样的话输出的CSV就像下面的结构:
- zh_CN_1.csv
- zh_CN_2.csv
- en_US_1.csv
- en_US_2.csv
每个csv里面可能有多条数据,就是那些国家语言以及page_id都相同的数据就放在同一个csv里.