在 PHP 中对多维数字数组进行排序
我在对多维数组进行排序时遇到问题。
数组看起来像:
$array = array( array("token" => array(100, 240, 348, 23, 17), array("token" => array(293, 28, 283, 2, 28), array("token" => array(842, 23, 72, 98, 114) );
现在我想按“列”对它们进行排序。这意味着,第一列数字 (100, 293, 842) 必须排序,然后是第二列(但保持第一列不变!可能会发生多行列具有相同数字的情况),依此类推。
实际上我尝试用 usort() 来做到这一点,但这仅在对第一列进行排序时才有效:
function do_sort($a, $b) {
$tok_a = $a["token"];
$tok_b = $b["token"];
if ($tok_a[0] <= $tok_b[0])
return false;
else
return true;
}
usort($array, "do_sort");
我该怎么做?谢谢
I have issues sorting an multidimensional array.
The array looks like:
$array = array( array("token" => array(100, 240, 348, 23, 17), array("token" => array(293, 28, 283, 2, 28), array("token" => array(842, 23, 72, 98, 114) );
Now I want to sort them by "column". That means, the first column of numbers (100, 293, 842) must be sorted, then the second column (but keeping the first column as it is! It may happen that the columns have the same number with multiple rows) and so on.
Actually I tried this to do with usort(), but this will work only when sorting the first column:
function do_sort($a, $b) {
$tok_a = $a["token"];
$tok_b = $b["token"];
if ($tok_a[0] <= $tok_b[0])
return false;
else
return true;
}
usort($array, "do_sort");
How can I do this? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是可能的解决方案:
代码:
输出:
Here's possible solution:
Code:
Output:
我想这会做你所追求的。我在这里做了一些假设(例如
$array
确实是一个数组,至少有一个子数组,所有子数组都有token code> 作为键,并且所有子数组具有相同数量的元素)。
输出:
I think this will do what you are after. I've made some assumptions here (such as
$array
is really an array, has at least one sub-array, all sub-arrays havetoken
as the key, and all sub-arrays have the same number of elements).Output:
你不能只是
或者我误解了这个问题吗?
Can't you just
Or have I misunderstood the question?