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
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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.