Click to See Complete Forum and Search --> : sorting array help


bsmbahamas
07-23-2007, 08:30 AM
hi guys,

i can never quite get sorting arrays to work :confused:

i have a flat database file, database.php ...

user1|4
user2|7
user3|15
user4|31
user5|1

i need a script that will read this file into an array then sort the users
in descending order using the number next to each user as the sorting
criteria so it ends up like this ...

user4|31
user3|15
shadow|7
admin|4
user5|1

note: I just want the array to be sorted into a second array, i don't want the order to be saved to the file ... so the file will remain the same, but the script will create a second array that is already sorted in order from highest to lowest, and i'll then code the script to make it display the top 10 users.

can you guys help me with this?

i tried using sort(), asort() and ksort() but they dont work, they treat each line as an entire element and sorts the results by name not by the numerical value.

thanks

tca
07-23-2007, 10:31 AM
See if this isn't about the same thing as you're trying to do:

http://www.webdeveloper.com/forum/showthread.php?t=155184

TC

bsmbahamas
07-23-2007, 11:08 AM
i don't quite understand mysql so i'm using a ordinary file
with the data dumped into it.

i was guessing that i would have to use keys to sort it.

I 'll try it out with what i think is useful from the link you
gave an see if i can get it to work.

thanks.

bsmbahamas
07-23-2007, 12:03 PM
his code does exactly what i want to achieve, but i'm not using mysql,
and can't quite figure out how to use it with a flat database file.

my database file database.php has the following in it ...
user1|7
user2|17
user3|1
user4|11
user5|30

$file = "database.php";
$myarray = file($database);

echo "<li>" . $myarray[0] . "</li>"
echo "<li>" . $myarray[1] . "</li>"

outputs ...

user1|7
user2|17


not ...

user1
7


and i think it needs to split the user1|7 into user1 & 7 first.

i think it is treating the whole line as one string rather than
2 values a user and a number

so maybe i need to use

for( $i = 0; $i <sizeof($myarray); $i++ ){
$myarray[$i] = explode("|",$myarray[$i]);
}

what do you think?

bsmbahamas
07-23-2007, 01:21 PM
$dbfile = "database.php";
$myarray = file($dbfile);

//trim whitespace
$myarray = array_map('trim',$myarray);

//create an associative array from each line
for( $i = 0; $i < sizeof($myarray); $i++ ){
$temp = explode("|",$myarray[$i]);
$mydb["$temp[0]"] = $temp[1];
}

//print the original order
echo "<p>"; print_r($mydb);

//sort by value
arsort($mydb);

//print the array sorted from highest to lowest
echo "<p>"; print_r($mydb);