PHP - 按键对多维数组进行排序 [英] PHP - sort multidimensional array by key
本文介绍了PHP - 按键对多维数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到了一个多维数组,可能如下所示:
I got a multidimensional array which may look like this:
$array[1][0] = "string";
$array[0][1] = "anotherstring";
$array[0][0] = "thirdstring";
$array[1][1] = "fourthstring";
我想按键对这个数组进行排序,使其看起来像这样:
I want to sort this array by keys so it looks like this:
$array[0][0] = "thirdstring";
$array[0][1] = "anotherstring";
$array[1][0] = "string";
$array[1][1] = "fourthstring";
目前我正在使用以下程序:
At the moment I am using the following procedure:
ksort($array);
foreach ($array as $key => $value) {
ksort($value);
$array[$key] = $value;
}
这确实工作得很好,但也许有更好的(内置)函数来做到这一点?
This does work perfectly, but maybe there is a better (in-built) function to do this?
推荐答案
您可以通过以下方式缩短循环:
You can shorten your loop with:
ksort($array);
foreach($array as &$value) {
ksort($value);
}
或者使用array_walk
:
ksort($array);
array_walk($array, 'ksort');
这篇关于PHP - 按键对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文