Jump to content

sorting multiple arrays by the same key


jdubwelch

Recommended Posts

i have three arrays:

[code]Array "ONE"
(
    [0] => Vince
    [1] => Papale
    [2] => 1
    [3] => 46
    [4] => 46
    [5] => 0
    [6] => 46
)
Array "TWO"
(
    [0] => Brian
    [1] => Pollard
    [2] => 10
    [3] => 293
    [4] => 29.3
    [5] => 4
    [6] => 77
)
Array "THREE"
(
    [0] => Johnny
    [1] => King
    [2] => 3
    [3] => 34
    [4] => 10.3
    [5] => 2
    [6] => 16
)[/code]

the arrays are named, ONE, TWO, and THREE.
i want to be able to sort them according to different keys.

for example: i want the arrays to be be in order of their 2nd key.

so the order would be:

TWO
THREE
ONE

How would i do that?

Link to comment
https://forums.phpfreaks.com/topic/28761-sorting-multiple-arrays-by-the-same-key/
Share on other sites

There are two different approaches. First of all I would put the arrays into one multidimensional array like this:
[code]<?php
$multiarray["one"] = array
(
    0 => Vince,
    1 => Papale,
    2 => 1,
    3 => 46,
    4 => 46,
    5 => 0,
    6 => 46
);
$multiarray["two"] = array
(
    0 => Brian,
    1 => Pollard,
    2 => 10,
    3 => 293,
    4 => 29.3,
    5 => 4,
    6 => 77
);
$multiarray["three"] = array
(
    0 => Johnny,
    1 => King,
    2 => 3,
    3 => 34,
    4 => 10.3,
    5 => 2,
    6 => 16
);
?>[/code]

Then, you could use this (but you will lose the key associations - i.e. the first array will be index [0] not index ["two"]):
[code]<?php
function sortArray($a, $b) {
    if($a[2] == $b[2]) { return 0; }
    return ($a[2] < $b[2]);
}

usort($multiarray, "sortArray");
?>[/code]

EDIT: I forgot to mention the other approach which would be to use the function array_multisort(). But, after realizing you would have to convert your arrays in such a way that the data would be in a fundamentally different format I decided against creating an example.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.