Jump to content

[SOLVED] Sorting Multipule Arrays


ILikeBread

Recommended Posts

Hi

 

I was hoping someone could help me with this as i have been struggling with it all weekend.

 

I have an few Arrays which i populate like this

 

Do {

$Array1[$row_SQLQueries['ID']] = $Dollars;
$Array2[$row_SQLQueries['ID']] = $Name;
$Array3[$row_SQLQueries['ID']] = $Username;

} while ($row_SQLQueries = mysql_fetch_assoc($SQLQueries));

 

// FYI - It ends up being about 1000 users.

 

What i want to do is sort $Dollars and display them in order of highest to lowest. (I can do that part fine)

 

function my_sort($a, $b)
{
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1;
}

usort($Array1, "my_sort");

 

 

What i have problems with is lining up the $Name and the $Username to the correct $Dollar amount.

 

I have this but obviously its wrong because it doesnt work

 

foreach ($Array1 as $Key => $SortedDollars)
{	
echo "RANK: " .$Key . " | NAME:".[Array2[$Key]] ." | USERNAME:".[Array3[$Key]] ." | DOLARS: " . $SortedDollars. "<BR>";
}

 

I have also tried

foreach ($Array1 as $Key => $SortedDollars)
{    
echo "RANK: " .$Key . " | NAME:". $Array2[$Key] ." | USERNAME:".$Array3[$Key] ." | DOLLARS: " . $SortedDollars. "<BR>";
}  

 

However it returns

-------------

RANK: 0 | NAME: | USERNAME: | DOLLARS: 23.77

RANK: 1 | NAME: | USERNAME: | DOLLARS: 11.7

RANK: 2 | NAME: | USERNAME: | DOLLARS: -27.2222222222

RANK: 3 | NAME: | USERNAME: | DOLLARS: -38.0102040816

ect ect

-----------

Name ($Array2[$Key]) and Username ($Array3[$Key]) return null.

 

I am probably going about this the complete wrong way. Any help would be much appreciated.

 

Thankyou

Link to comment
https://forums.phpfreaks.com/topic/153823-solved-sorting-multipule-arrays/
Share on other sites

Either Update yer sort function to include the other two arrays. keeping them all aligned.

its not hard to make yer own sort function,

<?php

$arr=array(5,4,3,2,1);
$arr2=array('a','b','c','d','e');
$c=count($arr);
$k=array_keys($arr);
print_r($arr);
print_r($arr2);

for($i=0;$i<($c-1);$i++)
{
  for($j=$i+1;$j<$c;$j++)
  {
  	if($arr[$k[$i]]>$arr[$k[$j]])
  	{
  		$t=$arr[$k[$i]];
  		$arr[$k[$i]]=$arr[$k[$j]];
  		$arr[$k[$j]]=$t;
  		$t=$arr2[$k[$i]];
  		$arr2[$k[$i]]=$arr2[$k[$j]];
  		$arr2[$k[$j]]=$t;
  		
  	}
  }
}
print_r($arr);
print_r($arr2);
?>


 

as a simple sorter, since we want to be shure the array element exists we pull the array keys, so it avoids errors if yer arrays use values instead.

 

in the swap routine, is where u add yer other arrays for swapping as well.

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.