-2

I've got an array as follows:

Array (
[id] => Array
    (
        [0] => 3321
        [1] => 3318
        [2] => 3320
        [3] => 3319
        [4] => 3324
        [5] => 3322
    )

[name] => Array
    (
        [0] => Carla Taku
        [1] => Honey-Pearl Te Moni
        [2] => Monique Koroua
        [3] => Summer Hellier
        [4] => Wayne Kahukiwa
        [5] => Natasha Merito
    )

[courses] => Array
    (
        [0] => 2
        [1] => 1
        [2] => 1
        [3] => 1
        [4] => 1
        [5] => 1
    )

)

I want to sort this by "name", but I can't work out how to do this. I can't make it multi-dimensional due to some other code. I've tried usort, ksort, array_sort, array_multisort, but I'm not experienced enough to sort this.

5
  • Do you mean sort all three based on sorting one column or sorting by last name? Commented Jun 12, 2014 at 3:39
  • @Anthony I want to sort all 3 if possible, based on the "name" column Commented Jun 12, 2014 at 3:42
  • Do you mean sort this on the basis of key like id,name,course .Please Give the details how you want to sort that will be helpful Commented Jun 12, 2014 at 3:43
  • 1
    us1.php.net/manual/en/function.array-multisort.php Commented Jun 12, 2014 at 3:43
  • @Anthony I've tried that, but wasn't sure what values to set it at? Any hints please? Commented Jun 12, 2014 at 3:50

3 Answers 3

4

I think array_multisort is what you are after:

array_multisort($array['name'], $array['id'], $array['courses']);
Sign up to request clarification or add additional context in comments.

2 Comments

You my friend are a legend! Thanks! I just couldn't work out how it was supposed to be ordered. :)
Nice and simple instead of my multi-line below, you learn something new everyday.
1

I just came across sorting stuff yesterday. Hopefully this could give you some hint.

function SortByName($a,$b){
    return strcasecmp($a['name'], $b['name']);
}

usort($YourArray, 'SortByName');

1 Comment

I have tried this, but I keep getting the error Undefined index: name? But if I echo the array after the function it's changed?
1

Sorry for not using your specific array, I got lazy. However this should work for you, easy as pie.

$ar = array(
    array("10", 11, 100, 100, "a"),
    array(1, 2, "2", 3, 1)
);

$temp = $ar[1];

$count = 0;

asort($ar[0]);
foreach ($ar[0] as $key => $value) {
    $ar[1][$count] = $temp[$key];
    $count++;
}

print_r($ar);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.