1

I got a 2d-array containing a "column" on which this whole array is to be sorted. As I learned here, it is quite straightforward using array_multisort. My problem is, that this to be sorted over column contains values that needs to be compared in an unusual way. So I thought of something like this:

function main(){
    $toBeSorted = array(array(...), ..., array(...));
    $sortColumnIndex = n;
    $sort_column = array();

    //Code copied from provided link
    foreach ($toBeSorted as $row)
        $sort_column []= $row[$sortColumnIndex];

    array_multisort($this->comparator(),$sort_column, $toBeSorted);
}

function comparator(a,b){
    return 1;
}

As you can see, I want to pass my comparator to that sort-function. I probably think to much in a non-php way.

2 Answers 2

0

There is the usort function, which sorts by using a callback.

Otherwise you could have a look at the array_walk and array_walk_recursive functions, which iterate over an array and apply a function to every member.

Sign up to request clarification or add additional context in comments.

2 Comments

is there another function that works like usort but returns an array of positions of the elements? Just like pythons numpy.argsort? Because otherwise I cannot keep track of the other columns to sort the 2d-arrays?
I don't think it exists. This is the list of all array sorting functions in PHP.
0

I solved it by transforming my sorting space in one, that array_multisort can handle:

...

$sortColumn = array();
foreach($toBeSorted as $value){
     $sortColumn[] = $this->transform($value);
}
array_multisort($sortColumn, $toBeSorted);

...

my transformation function simply does everything I imagined the callback would do.

function transform($value){
    //i.e. return real part of complex number
    //or parse strings or any kind of strange datatypes
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.