2D Array Sorting, Help !

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
phpbaby2009
Forum Commoner
Posts: 31
Joined: Sun Nov 16, 2008 8:20 pm

2D Array Sorting, Help !

Post 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:
JasonDFR
Forum Commoner
Posts: 40
Joined: Wed Jan 07, 2009 3:51 am

Re: 2D Array Sorting, Help !

Post by JasonDFR »

How do you want your data to be sorted?

You need to define a sorting function when using usort.
NOmeR1
Forum Newbie
Posts: 8
Joined: Sat Feb 14, 2009 8:32 am

Re: 2D Array Sorting, Help !

Post 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
User avatar
phpbaby2009
Forum Commoner
Posts: 31
Joined: Sun Nov 16, 2008 8:20 pm

Re: 2D Array Sorting, Help !

Post 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.
Post Reply