phparrayssortingmultidimensional-arrayarray-multisort

passed parameter to array_multi_sort?


I have an base array

$base =array(
            "A1" =array();
            "A2" =array();
            "A3" =array();
            "A4" =array();
    );

and array of condition will use to sort

$condition  = array("A1" => "SORT_ASC",
                    "A4" => 'SORT_ASC',
                    "A3" => 'SORT_DESC'
                   );

I tried create a function like this to return a array_multi_sort

function sort_by_condition($condition) {


    return  array_multisort(
           $base['A1'], SORT_ASC, SORT_STRING,
           $base['A4'], SORT_ASC,SORT_NUMERIC, 
           $base['A3'], SORT_DESC,SORT_NUMERIC,
           $base['A2'],//default
           );

}

But I dont know how can I return something like this?


Solution

  • You may need to give the proper array keys to array multisort:

    $ar = array(
           array("10", 11, 100, 100, "a"),
           array(   1,  2, "2",   3,   1)
          );
    
    array_multisort($ar[0], SORT_ASC, SORT_STRING,
                    $ar[1], SORT_NUMERIC, SORT_DESC);
    

    This is from the manual but I assume your example would become more like this:

     array_multisort( $base['A1'], SORT_ASC, SORT_STRING,
                      $base['A2'], SORT_ASC, SORT_NUMERIC, 
                      etc...
                    );
    

    I realize you have probably read it a few times but see the examples in the manual and try making it work outside the function first. Good-luck! :)