Page 1 of 1

2D Array Sorting, Help !

Posted: Fri Mar 27, 2009 8:22 pm
by phpbaby2009
Hi everyone. I'm not getting expected result using usort.

Can you help please ?
fields : name, address, state, due amount. These are loaded from a flatfile text file.

$data[1][0]="Mr. Jack"
$data[1][1]="122 Jackson Ville"
$data[1][2]="Florida"
$data[1][3]="$900.50"

$data[2][0]="Mr. Brown"
$data[2][1]="122 Jackson Ville"
$data[2][2]="NY"
$data[2][3]="$600.50"

$data[3][0]="Mrs Smith"
$data[3][1]="143 Clorado"
$data[3][2]="NC"
$data[3][3]="$450.44"
usort($data[][3]); // this doesn't help me.

thanks guys. PHP has so many functions, but I'm lost. What should I do ? Please help ! :roll:

Re: 2D Array Sorting, Help !

Posted: Sat Mar 28, 2009 1:53 am
by JasonDFR
How do you want your data to be sorted?

You need to define a sorting function when using usort.

Re: 2D Array Sorting, Help !

Posted: Sat Mar 28, 2009 2:16 am
by NOmeR1
If I understood correctly, you need something like this

Code: Select all

<?php
function cmp($a,$b) {
    $price1 = $a[3]; // Price is a thrid element of array
    $price2 = $b[3]; // Price is a thrid element of array
    $price1 = substr($price1,1); // Unset first symbol of first price '$'
    $price2 = substr($price2,1); // Unset first symbol of second price '$'
    return $price1>$price2?1:($price1<$price2?-1:0);
}
 
$data[1][0]="Mr. Jack";
$data[1][1]="122 Jackson Ville";
$data[1][2]="Florida";
$data[1][3]="$600.50";
 
$data[2][0]="Mr. Brown";
$data[2][1]="122 Jackson Ville";
$data[2][2]="NY";
$data[2][3]="$900.50";
 
$data[3][0]="Mrs Smith";
$data[3][1]="143 Clorado";
$data[3][2]="NC";
$data[3][3]="$105.44";
 
$data[4][0]="Mrs Noname";
$data[4][1]="122 Jackson Ville";
$data[4][2]="NC";
$data[4][3]="$15.44";
 
usort($data,"cmp");
print_r($data);
?>
This code will sort $data by third element

Re: 2D Array Sorting, Help !

Posted: Sun Mar 29, 2009 2:10 pm
by phpbaby2009
Thank you so much.

I'm inside a function with loads of variables. Does PHP offer function inside a function or should I have to again use global $bla,$bla............................... a lot of that, again in this function ?

This function didn't work for me. I know it's my bad codes. I have decided that the column I want to sort can have texts, numbers and eve Unicode characters. I guess, I just change the column value there [3] to anything I want ?


thank you.