array_multisort and dynamic variable options

前端 未结 5 852
孤独总比滥情好
孤独总比滥情好 2020-11-27 08:53

Im trying to sort any array with array_multisort and everything is working great. However, based on conditions in my script, I need to change the options. So What I have s

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 09:26

    To add onto the existing answers, just thought I would add a little something. For anyone passing the desired "sort by" as a comma-separated $_POST variable (or any comma-separated variable for that matter):

    //$_POST["sort_by"] = "column_A DESC, column_B ASC, columns_C DESC";
    $sort_bys = explode(",", $_POST["sort_by"]);
    $dynamicSort = array();
    foreach($sort_bys as $sort_by){
        $sort_by2 = trim(str_replace('DESC','',$sort_by));
        $direction = (strpos($sort_by, 'DESC') !== false)?SORT_DESC:SORT_ASC;
        $$sort_by2  = array_column($array_to_sort, $sort_by2);
        $dynamicSort[] = &$$sort_by2;
        $dynamicSort[] = $direction;
        $dynamicSort[] = SORT_NUMERIC; //or SORT_STRING or SORT_REGULAR ...
    }    
    $param = array_merge($dynamicSort, array(&$array_to_sort));
    call_user_func_array('array_multisort', $param);
    

提交回复
热议问题