PHP按索引对2d数组进行排序(非关联) [英] PHP sort 2d array by index (non-associative)

查看:92
本文介绍了PHP按索引对2d数组进行排序(非关联)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码无法正常运行,但是它表明了我正在尝试做的事情:

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;
}

有一种更好的方法可以做到这一点.我一直在检查ksort()multisort()和各种各样的东西,直到我厌倦了尝试将其全部整理出来.

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)
);

...,我想按列索引排序.例如,列[1]会给出以下结果:

...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)
);

有人链接吗(我确定之前已经有人问过这个链接),或者有人可以说您肯定需要foosort".非常感谢.

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

推荐答案

您无法避免创建仅包含一列的数组:

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);

这将同时对两个数组进行排序,以便随后将整个数组按照与$ sort_column数组相同的顺序进行排序.

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

从PHP 5.3开始,您可以使用闭包(通过$i进入函数),方法如下:定义cmp函数:

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) { ... };

这篇关于PHP按索引对2d数组进行排序(非关联)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆