duanchao4445 2009-03-30 07:47
浏览 73
已采纳

多次在同一个数组上使用array_multisort?

I have a largish table of data pulled from my database (~1500 rows, each with 10-15 fields) and I'm doing a number of filters and generating some stats and storing these in an excel spreadsheet for the user to download.

Rather than hit the database with the same fairly-complicated query over and over with only minor modifications (to the WHERE and ORDER BY), I'm doing one trip to the DB, putting the results into one big array and then using array_filter and array_multisort to get my new views of the data.

I'm new to array_multisort so I'll post what I've done here for critique.

// an numerical array of associative arrays
$records = $dbResult->convertToArray();

$fields = $dbResult->getFieldNames();

// this is run once at the start
$sortArr = array();
foreach ($fields as $field) $sortArr[$field] = array();

foreach ($records as $r) {
    foreach ($r as $key => $value) {
        $sortArr[$key][] = $value;
    }
}

// and then to sort:
array_multisort(
    $sortArr['Date Completed'], SORT_DESC,
    $sortArr['Last Name'], SORT_ASC,
    $sortArr['First Name'], SORT_ASC,
    $sortArr['Course'], SORT_ASC,
    $records
);

This works fine, though the initial "copy the entire result into another array" seems strange to me. The problem occurs when I need to sort the list again. I have the feeling that my $sortArr needs to stay in sync with the $records array, but that it gets broken after each sort.

I'm not even sure that this is the intended use of array_multisort, so I might be way off track here. Can anyone give some advice or tips? How do you sort multidimensional arrays?

  • 写回答

1条回答 默认 最新

  • dou426098 2009-03-30 08:22
    关注

    Here's what I ended up going with. It's a slightly modified version of a function posted by martin in the comments on the usort page in the PHP manual.

    function arfsort( &$array, $fieldList ){
        if (!is_array($fieldList)) {
            $fieldList = array(array($fieldList, SORT_ASC));
        } else {
            for ($i = 0; $i < count($fieldList); ++$i) {
                if (is_array($fieldList[$i])) {
                    if (!isset($fieldList[$i][1])) $fieldList[$i][1] = SORT_ASC;
                } else {
                    $fieldList[$i] = array($fieldList[$i], SORT_ASC);
                }
            }
        }
        $GLOBALS['__ARFSORT_LIST__'] = $fieldList;
        usort( $array, 'arfsort_func' );
    
    }
    
    function arfsort_func( $a, $b ){
        foreach( $GLOBALS['__ARFSORT_LIST__'] as $f ) {
            $strc = strcasecmp($b[$f[0]], $a[$f[0]]);
            if ( $strc != 0 ){
                return $strc * (!empty($f[1]) && $f[1] == SORT_DESC ? 1 : -1);
            }
        }
        return 0;
    }
    

    I've hopefully made the function a little more robust than the original solution. Usage:

    arfsort($my2DArray, "id");  // just sort by the id field, ascending
    // sort by these lastName then firstName, ascending
    arfsort($my2DArray, array("lastName", "firstName"));
    
    arfsort($my2DArray, array(
        array("date", SORT_DESC),    // sort by date DESC
        array("lastName", SORT_ASC), // then by last name ascending
        array("firstName"),          // SORT_ASC is the default
        "middleInitial"              // and you don't need to wrap stuff in an array.
    ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况