Usort Function Help Needed (Array Sorting)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

Usort Function Help Needed (Array Sorting)

Post by kaisellgren »

Hi,

My PHP code:

Code: Select all

<?php

$a = array(array(array('fifth',5),array('sixth',15),array('fourth',1)),array(array('second',5),array('third',15),array('first',1)));

function cmp($a, $b)
{
  if ($a[1]==$b[1])
    return 0;
  return ($a[1]  < $b[1]) ? -1 : 1;
}

usort($a, "cmp"); 
var_dump($a);

?>
I need to sort the arrays in correct order: first, second, third, fourth, fifth, sixth. But it does not work. Any ideas?
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

Your $a array has two elements and not six as you probably expect. You have to "flatten" it first (e.g. array_merge($a[0], $a[1]))
And php has no idea on why "third" should be before "fourth". You need a function that converts english numerals to numbers.
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

Post by kaisellgren »

stereofrog wrote:Your $a array has two elements and not six as you probably expect. You have to "flatten" it first (e.g. array_merge($a[0], $a[1]))
And php has no idea on why "third" should be before "fourth". You need a function that converts english numerals to numbers.
Hi that's why I have those numbers so that PHP knows that third becomes before fourth.

Thanks for your help. I decided to make a new array based on existing array and I made my new array different. Now it has six elements and it's working properly :)
Post Reply