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

This code does not work correctly, 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 should be a much better way to do this. I studied ksort(), multisort()and various kinds, as long as I'm not tired, trying to sort things out.

The situation is this: I have a 2nd array ...

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

... and I want to sort by column index. Say a column [1]will give the following result:

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

Someone has a link (I'm sure this was asked before), or someone may say "you need it foosort, definitely." Many thanks.

+3
source share
3 answers

array_multisort , .

, :

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

array_multisort($sort_column, $a);

, , $sort_column.

PHP 5.3 ( $i ), cmp :

$cmp = function($x, $y) use ($i) { ... };
+7

use $i:

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

Source: https://habr.com/ru/post/1776593/


All Articles