Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sort 2d array by index (non-associative)

Tags:

php

sorting

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.

like image 669
Ben Avatar asked Sep 11 '26 03:09

Ben


1 Answers

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) { ... };
like image 72
AndreKR Avatar answered Sep 12 '26 18:09

AndreKR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!