简体   繁体   English

PHP-按键对多维数组排序

[英]PHP - sort multidimensional array by key

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

Or use array_walk : 或使用array_walk

ksort($array);
array_walk($array, 'ksort');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM