3

This code does not run properly, but it suggests what I am trying to do:

function sort_2d_by_index($a,$i) {
  function cmp($x, $y) {
    // Nested function, can't find $i
    // (global $i defeats the purpose of passing an arg)
    if ($x[$i] == $y[$i]) { return 0; }
    return ($x[$i] < $y[$i]) ? -1 : 1;
  }

  usort($a,"cmp");
  return $a;
}

There HAS to be a much better way to do this. I've been examining ksort(), multisort(), and all sorts of sorts until I'm sort of tired trying to sort it all out.

The situation is this: I've got a 2-d array...

array(
  array(3,5,7),
  array(2,6,8),
  array(1,4,9)
);

...and I want to sort by a column index. Say, column [1], would give this result:

array(
  array(1,4,9),
  array(3,5,7),
  array(2,6,8)
);

Does someone have a link (I'm sure this has been asked before), or could someone say "you need foosort, definitely". Thanks very much.

0

3 Answers 3

8

In the documentation of array_multisort it is mentioned that it can be used for this kind of thing.

You can't avoid creating an array that consists of only one column:

$sort_column = array();
foreach ($a as $row)
    $sort_column []= $row[1]; // 1 = your example

array_multisort($sort_column, $a);

This sorts both arrays synchronously so that afterwards your whole array is sorted in the same order as the $sort_column array is.

As of PHP 5.3 you can use a closure (pass $i into the function) by defining your cmp function like this:

$cmp = function($x, $y) use ($i) { ... };
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the closure link, too. Turns out the array_multisort solution is The One, until PHP 5.3 is more widespread. I had had a look at the documentation but didn't find an explanation as good as this one. Too bad I can't accept twice, this answer is great :)
1

You can use use to access $i:

function cmp($x, $y) use ($i) {
    // $i now available
    if ($x[$i] == $y[$i]) { return 0; }
    return ($x[$i] < $y[$i]) ? -1 : 1;
}

Comments

0

http://www.php.net/manual/en/function.sort.php#99419

phpdotnet at m4tt dot co dot uk

Simple function to sort an array by a specific key. Maintains index association.

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.