PHP排序多维数组的维数

时间:2022-05-05 21:38:23

there's nothing much to explain, i'll straight get to the sample code:

没什么好解释的,我直接去看看样本代码:

<?php
$array[0]['a'] = 3;
$array[0]['b'] = 2;
$array[0]['c'] = 4;
$array[0]['d'] = 1;

$array[1]['a'] = 4;
$array[1]['b'] = 2;
$array[1]['c'] = 3;
$array[1]['d'] = 1;

$array[2]['a'] = 1;
$array[2]['b'] = 2;
$array[2]['c'] = 4;
$array[2]['d'] = 3;
?>

after sorting, it should look like:

排序后,应该是:

<?php

$array[0]['d'] = 1;
$array[0]['b'] = 2;
$array[0]['a'] = 3;
$array[0]['c'] = 4;


$array[1]['d'] = 1;
$array[1]['b'] = 2;
$array[1]['c'] = 3;
$array[1]['a'] = 4;

$array[2]['a'] = 1;
$array[2]['b'] = 2;
$array[2]['d'] = 3;
$array[2]['c'] = 4;
?>

can't really get my head around it. in a nutshell: i don't wanna sort whole array, but instead i wanna sort specific dimensions of an array

我真搞不懂。简单地说:我不想对整个数组进行排序,而是想对数组的特定维度进行排序

2 个解决方案

#1


0  

Use foreach to go down a level, and then sort each subarray. There are a few ways you can do this:

使用foreach下行一个级别,然后对每个子数组进行排序。有几种方法可以做到这一点:

foreach($arr as &$sub) asort($sub);
// OR
foreach($arr as $k=>$sub) asort($arr[$k]);
// OR
foreach(array_keys($arr) as $k) asort($arr[$k]);

#2


0  

You have to sort directly you index :

你必须直接排序你的索引:

ksort($array[0]);

ksort($阵列[0]);

To sort all index :

对所有索引进行排序:

foreach($array as $index => $val){ 
    asort($val);
    $array[$index] = $val; 
}

#1


0  

Use foreach to go down a level, and then sort each subarray. There are a few ways you can do this:

使用foreach下行一个级别,然后对每个子数组进行排序。有几种方法可以做到这一点:

foreach($arr as &$sub) asort($sub);
// OR
foreach($arr as $k=>$sub) asort($arr[$k]);
// OR
foreach(array_keys($arr) as $k) asort($arr[$k]);

#2


0  

You have to sort directly you index :

你必须直接排序你的索引:

ksort($array[0]);

ksort($阵列[0]);

To sort all index :

对所有索引进行排序:

foreach($array as $index => $val){ 
    asort($val);
    $array[$index] = $val; 
}