Page 1 of 1

Usort Function Help Needed (Array Sorting)

Posted: Fri Sep 07, 2007 12:17 am
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?

Posted: Fri Sep 07, 2007 4:23 am
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.

Posted: Fri Sep 07, 2007 7:46 am
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 :)