写一个二维数组排序算法函数,可以调用php内置函数,能够具有通用性

    xiaoxiao2024-04-21  10

    <?php     $data = array();     $data[] = array('volume' => 67, 'edition' => 2);     $data[] = array('volume' => 86, 'edition' => 1);     $data[] = array('volume' => 85, 'edition' => 6);     $data[] = array('volume' => 98, 'edition' => 2);     $data[] = array('volume' => 86, 'edition' => 6);     $data[] = array('volume' => 67, 'edition' => 7);        // 取得列的列表     foreach ($data as $key => $row)     {         $volume[$key]  = $row['volume'];         $edition[$key] = $row['edition'];     }     $ret = arraySort($data, 'volume', 'desc');     print_r($ret);     /**      * @desc arraySort php二维数组排序 按照指定的key 对数组进行排序      * @param array $arr 将要排序的数组      * @param string $keys 指定排序的key      * @param string $type 排序类型 asc | desc      * @return array      */     function arraySort($arr, $keys, 0) {         $keysvalue = $new_array = array();         foreach ($arr as $k => $v){             $keysvalue[$k] = $v[$keys];         }         $type == 'asc' ? asort($keysvalue) : arsort($keysvalue);         reset($keysvalue);         foreach ($keysvalue as $k => $v) {            $new_array[$k] = $arr[$k];         }         return $new_array;     }

    ?>

    主要就是利用数组的key进行排序,然后按照key排序的数组在循环原来的数组即可。

    打印的结果如下:

    Array (     [0] => Array         (             [volume] => 67             [edition] => 2         )     [1] => Array         (             [volume] => 86             [edition] => 1         )     [2] => Array         (             [volume] => 85             [edition] => 6         )     [3] => Array         (             [volume] => 98             [edition] => 2         )     [4] => Array         (             [volume] => 86             [edition] => 6         )     [5] => Array         (             [volume] => 67             [edition] => 7         ) ) Array (     [0] => 67     [1] => 86     [2] => 85     [3] => 98     [4] => 86     [5] => 67 ) ===== Array (     [3] => 98     [4] => 86     [1] => 86     [2] => 85     [5] => 67     [0] => 67 ) Array (     [3] => Array         (             [volume] => 98             [edition] => 2         )     [4] => Array         (             [volume] => 86             [edition] => 6         )     [1] => Array         (             [volume] => 86             [edition] => 1         )     [2] => Array         (             [volume] => 85             [edition] => 6         )     [5] => Array         (             [volume] => 67             [edition] => 7         )     [0] => Array         (             [volume] => 67             [edition] => 2         ) )

    转载请注明原文地址: https://ju.6miu.com/read-1288198.html
    最新回复(0)