Daman
Daman

Reputation: 521

Sort a 2d array by a column's values

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

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

Upvotes: 0

Views: 119

Answers (2)

Emissary
Emissary

Reputation: 10148

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:

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

It only took 20 minutes... :(

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

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227240

I like to use usort to solve these problems.

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

Upvotes: 1

Related Questions