按PHP中的值排序多维数组

时间:2021-01-08 21:32:36

I have an array fetched from mysql database tables of type. I want to sort it in order of particular value.

我有一个从类型的mysql数据库表中获取的数组。我想按特定价值排序。

$arr1=array(array(12, 8, 5, 34),
        array(54, 87, 32, 10),
        array(23, 76, 98, 13),
        array(53, 16, 24, 19));

How can i sort it by value? Like sorting by 2nd value should result to.

我怎样才能按价值排序?像第二个值的排序应该导致。

$arr1=array(array(12, 8, 5, 34),
        array(53, 16, 24, 19),
        array(23, 76, 98, 13),
        array(54, 87, 32, 10));

2 个解决方案

#1


1  

I like to use usort to solve these problems.

我喜欢用usort来解决这些问题。

$sortKey = 1;
usort($arr1, function($a, $b) use($sortKey){
    return $a[$sortKey] - $b[$sortKey];
});

#2


1  

Got to agree with @RocketHazmat, array_multsort is a royal pain in the backside. usort is much easier to follow but I thought I'd have a go anyway:

得到了@RocketHazmat的同意,array_multsort是背后的皇家痛苦。 usort更容易理解,但我认为我还有一个去:

$sortKey = 1;
array_multisort(array_map(function($v) use($sortKey){
    return $v[$sortKey];
}, $arr1), $arr1);

It only took 20 minutes... :(

它花了20分钟...... :(

Here's a demo: http://ideone.com/2rZYIz

这是一个演示:http://ideone.com/2rZYIz

#1


1  

I like to use usort to solve these problems.

我喜欢用usort来解决这些问题。

$sortKey = 1;
usort($arr1, function($a, $b) use($sortKey){
    return $a[$sortKey] - $b[$sortKey];
});

#2


1  

Got to agree with @RocketHazmat, array_multsort is a royal pain in the backside. usort is much easier to follow but I thought I'd have a go anyway:

得到了@RocketHazmat的同意,array_multsort是背后的皇家痛苦。 usort更容易理解,但我认为我还有一个去:

$sortKey = 1;
array_multisort(array_map(function($v) use($sortKey){
    return $v[$sortKey];
}, $arr1), $arr1);

It only took 20 minutes... :(

它花了20分钟...... :(

Here's a demo: http://ideone.com/2rZYIz

这是一个演示:http://ideone.com/2rZYIz