I have some id's and distances in an array, when I try to sort them by the distances it doesn't seem to work. Here's my code:

$sortarray = array($id=>$distance);
asort($sortarray);
foreach ($sortarray as $key => $val) {
    echo "$key = $val";
}

The results come up as 1=10.2, 2=6.8, 3=9.7
I want the results to come up as 2=6.8, 3=9.7, 1=10.2
So they are ordering by the distance.
Any help here please!!!???!!!😕

    It looks like your distances are strings rather than numbers, so "10" < "6".

      So how do i put them in an order, they are just coming out ordered by the id.
      They are shown in order of id not distance

        hmm... perhaps I am wrong. This seems to work:

        $array = array(
            1 => "10.2",
            2 => "6.8",
            3 => "9.7"
            );
        asort($array);
        print_r($array);

          My results don't seem to come out like:

          array(
          [0]=10
          [1]=12
          [2]=8
          )
          they come out like:

          array(
          [0]=10
          )
          array(
          [1]=12
          )

            Oh wait, you have a 2-D array? Why not provide the smallest and simplest code that demonstrates the problem?

              This is my code, the distancetocleaner isworked out in a function higher up the page, with this code:

              function calc_postcode_seperation($pcodeA,$pcodeB) 
              
              { 
              
              // PCODE A 
              
              $result=mysql_query("SELECT * FROM postcodes WHERE Pcode='$pcodeA' LIMIT 1"); 
              
              $row=mysql_fetch_array($result); 
              
              $gridn[0]=$row[Grid_N]; 
              
              $gride[0]=$row[Grid_E]; 
              
              // PCODE B 
              $result=mysql_query("SELECT * FROM postcodes WHERE Pcode='$pcodeB' LIMIT 1"); 
              
              $row=mysql_fetch_array($result); 
              
              $gridn[1]=$row[Grid_N]; 
              
              $gride[1]=$row[Grid_E]; 
              
              // TAKE GRID REFS FROM EACH OTHER. 
              
              $distance_n=$gridn[0]-$gridn[1]; 
              
              $distance_e=$gride[0]-$gride[1]; 
              
              // CALCULATE THE DISTANCE BETWEEN THE TWO POINTS 
              
              $hypot=sqrt(($distance_n*$distance_n)+($distance_e*$distance_e)); 
              
              $text .='Distance between '.$pcodeA.' and '.$pcodeB.' is: '.round($hypot/1000*0.6214,2).'miles'; 
              $distance .=round($hypot/1000*0.6214,2);
              return $distance; 
              }
              

              And here's all the code. The results are coming out like so:

              Array
              (
              [470] => 176.37
              )

              Array
              (
              [470] => 176.37
              )

              Array
              (
              [483] => 129.17
              )

              Array
              (
              [483] => 129.17
              )

              $sorter = "SELECT * FROM directory WHERE authorised = 'Y'";
              $sorterResults = mysql_query($sorter);
              while ($sorterRow = mysql_fetch_array ($sorterResults)){
              	$sortpostcode = $sorterRow["postcode"];
              	$sortid = $sorterRow["id"];
              	$checksortpost = substr("$sortpostcode",0,4);
              	$distancetocleanersort = calc_postcode_seperation("$dir1","$checksortpost");
              //echo "$distancetocleanersort<br>";
              $sortarray = array($sortid=>$distancetocleanersort);
              
              echo "<pre>"; 
              print_r($sortarray); 
              echo "</pre>"; 
              asort($sortarray); 
              echo "<pre>"; 
              print_r($sortarray); 
              echo "</pre>";	
              }
              

                Okay here's the simplest version:

                $sortarray = array($sortid=>$distancetocleanersort);
                foreach ($sortarray as $key => $val) {
                	IF ($sortsubscription=='FREE' AND $distancetocleanersort<$dist AND $sortauth =='Y' AND $sortid==$key){
                                                asort($sortarray);
                		print_r($sortarray);
                }}
                

                Results for this are:

                Array ( [637] => 13.95 )
                Array ( [639] => 12.15 )
                Array ( [658] => 16.53 )

                  And what's the input data? And what is the result supposed to be?

                  If you have an array of arrays then asort() isn't likely to do what you want, because it will be trying to see if one array is less than another. [man]usort[/man] or [man]uasort[/man] allow sorting with arbitrary comparison criteria.

                    The results are supposed to be:

                    Array ( [639] => 12.15 )
                    Array ( [637] => 13.95 )
                    Array ( [658] => 16.53 )

                    The input data is comparing 2 post codes.

                    So will uasort sort this do you think?

                    I need it to be ordered by the results on the right hand side ($val)

                    Array ( [476] => 169.1 )
                    Array ( [521] => 89.92 )
                    Array ( [549] => 112.98 )
                    Array ( [564] => 112.46 )
                    Array ( [593] => 75.58 )
                    Array ( [594] => 75.58 )
                    Array ( [620] => 74.11 )
                    Array ( [637] => 13.95 )
                    Array ( [639] => 12.15 )
                    Array ( [658] => 16.53 )
                    Array ( [662] => 72.45 )
                    Array ( [664] => 64.23 )
                    Array ( [665] => 87.22 )
                    Array ( [669] => 74.3 )
                    Array ( [682] => 297.7 )
                    Array ( [742] => 68.79 )
                    Array ( [757] => 69.11 )

                      Is it maybe because the function is higher up the page and not in the select statement with the rest of it? Just a thought cheers!

                      😕 😕 😕

                        Could you do the following to further illustrate for us exactly what the array to be sorted looks like?

                        // preceding code to get to this point . . .
                        // . . . then . . .
                        $sortarray = array($sortid=>$distancetocleanersort);
                        printf("<pre>%s</pre>\n", print_r($sortarray, 1));
                        

                        Copy and paste the results of that printf between

                         tags here, and then we'll  know what it is we're dealing with. (If the result is really long, just truncate it after enough data is shown to clearly establish the array structure.)

                          It looks like this when I run your code.

                          They order by the id in []'s just need them to order by the other values on the right.

                          Array
                          (
                              [476] => 169.1
                          )
                          
                          Array
                          (
                              [521] => 89.92
                          )
                          
                          Array
                          (
                              [549] => 112.98
                          )
                          
                          
                          

                            Errr... excerpting from the earlier code...

                            while ($sorterRow = mysql_fetch_array ($sorterResults)){ 
                            
                            //echo "$distancetocleanersort<br>"; 
                            $sortarray = array($sortid=>$distancetocleanersort);
                            
                            asort($sortarray);
                            }
                            

                            $sortarray only contains one element. And with only one element, sorting doesn't achieve very much.

                            I think you wanted

                            $sortarray[$sortid]=$distancetocleanersort;
                            

                            And don't sort until after the loop.

                              Okay so i've done this and it's working in the print_r which is brilliant but how do i echo the results normally, so just the id = distance without array etc.

                              while ($sorterRow = mysql_fetch_array ($sorterResults)){
                              $sortarray[$sortid]=$distancetocleanersort; 
                              asort($sortarray);}
                              print_r($sortarray);
                              

                              Results now:

                              Array ( [639] => 12.15 [637] => 13.95 [658] => 16.53 [664] => 64.23 [742] => 68.79 [757] => 69.11 [662] => 72.45 [620] => 74.11 [669] => 74.3 [593] => 75.58 [594] => 75.58 [783] => 78.83 [665] => 87.22 [521] => 89.92 [766] => 90.1 [778] => 111.83 [564] => 112.46 [549] => 112.98 [476] => 169.1 [682] => 297.7 ) 
                              

                                Can I somehow put this into my select statement after all this is worked out so $val AS distance or something like that?

                                I want to show all the details for that id now, I have this

                                $sortid = $sorterRow["id"];
                                $sortsubscription = $sorterRow["subscription"];
                                $sortauth = $sorterRow["authorised"];
                                $sortco = $sorterRow["company"];

                                And would like them to be listed in this new order

                                  MitchEvans wrote:

                                  how do i echo the results normally, so just the id = distance without array etc.

                                  Don't use print_r, then. print_r is for debugging purposes to help you look at your data to see if there is something wrong with it (as in this case). There are whole pile of other functions and language constructs for putting strings together and outputting them.

                                  Can I somehow put this into my select statement

                                  You mean you want an ORDER BY clause in your query?

                                    Well I have one select atatement where this array is built up in the correct order, but now I need to get other data from the database according to which id's have been chosen in this array.
                                    The code below still brings them up in no order, but echo's the order they should be in by distance and id before the actual results appear.

                                    Here's my full code so you can understand my needs, thanks a bunch!

                                    $sorter = "SELECT * FROM directory WHERE authorised = 'Y' ";
                                    $sorterResults = mysql_query($sorter);
                                    while ($sorterRow = mysql_fetch_array ($sorterResults)){
                                    	$sortpostcode = $sorterRow["postcode"];
                                    	$sortid = $sorterRow["id"];
                                    	$sortsubscription = $sorterRow["subscription"];
                                    	$sortauth = $sorterRow["authorised"];
                                    	$sortco = $sorterRow["company"];
                                    	$checksortpost = substr("$sortpostcode",0,4);
                                    	$distancetocleanersort = calc_postcode_seperation("$dir1","$checksortpost");
                                    
                                    $sortarray[$sortid]=$distancetocleanersort;
                                    
                                    }
                                    asort($sortarray);
                                    foreach ($sortarray as $key => $val) {	
                                    
                                    echo "$val = $key<br>";}
                                    
                                    //////////////////////////////////////////////////////////////TODAY
                                    
                                    //Show results for users that have been authorised by administrator and their clean types have been checked by the user
                                    $directory = "SELECT * FROM directory WHERE authorised = 'Y'";
                                    
                                    $directoryResults = mysql_query($directory);
                                    $count_result = mysql_num_rows($directoryResults);
                                    while ($directoryRow = mysql_fetch_array ($directoryResults)){
                                    $id = $directoryRow["id"];
                                    $company = $directoryRow["company"];
                                    $website = $directoryRow["website"];
                                    $details = $directoryRow["details"];
                                    $addressline = $directoryRow["address"];
                                    $postcode = $directoryRow["postcode"];
                                    $number = $directoryRow["number"];
                                    $email = $directoryRow["email"];
                                    $image = $directoryRow["image"];
                                    $clean1_id = $directoryRow["clean1_id"];
                                    $clean2_id = $directoryRow["clean2_id"];
                                    $clean3_id = $directoryRow["clean3_id"];
                                    $clean4_id = $directoryRow["clean4_id"];
                                    $clean5_id = $directoryRow["clean5_id"];
                                    $clean6_id = $directoryRow["clean6_id"];
                                    $subscription = $directoryRow["subscription"];
                                    $authorised = $directoryRow["authorised"];
                                    
                                    $checkpost = substr("$postcode",0,4);
                                    IF (strlen($postcode)=='6'){
                                    $checkpost=substr("$postcode",0,3);	}
                                    
                                    
                                    $number1= substr("$number",-4);
                                    
                                    $distancetocleaner = calc_postcode_seperation("$dir1","$checkpost");
                                    
                                    IF ($website==''){
                                    	$company=$company;}
                                    ELSE $company="<a target='_blank' href='http://$website'>$company</a>";
                                    
                                    echo"<form method = 'POST' action='compare.php'>";
                                    //Show all details if customer has paid account and is within distance specified by search
                                    
                                    IF ($subscription=='PAID' AND $distancetocleaner<$dist AND $authorised =='Y'){
                                    
                                    echo"
                                    
                                    <center>
                                    <table bgcolor='#ffffcc' width='50%' border ='1' bordercolor='navy'>
                                    <tr>
                                    <td>$company</td><th valign='center' rowspan='5' width='90'><center><img width='90' src='upload/$image'></center></th>
                                    </tr>
                                    
                                    
                                    <tr>
                                    <td>$addressline, <a href='http://www.multimap.com/map/browse.cgi?pc=$postcode' target='_blank'>$postcode</a></td>
                                    </tr>
                                    
                                    <tr>
                                    <td>$number</td>
                                    </tr>
                                    <tr>
                                    <td><a href='mailto:$email?subject=I found you on Cleaners Directory'>$email</a></td>
                                    </tr>
                                    <tr><td>
                                    This cleaner is $distancetocleaner miles from you!
                                    </td></tr>
                                    <tr><td>
                                    Compare:
                                    <input type='checkbox' name='compare[]' value='$id'/>
                                    </td><td>
                                    <a href='fulldetails.php?id=$id'>More Details</a></td></tr>
                                    </table></center><p>";
                                    $count++;
                                    }
                                    //Only show some details for users that have free account
                                    ELSEIF ($subscription == 'FREE' AND $distancetocleaner<$dist AND $authorised =='Y'){
                                    echo"
                                    <center>
                                    <table bgcolor='#ffffcc' width='50%' border ='1' bordercolor='navy'>
                                    <tr>
                                    <td>$company</td>
                                    </tr>
                                    <tr>
                                    <td>$addressline, $postcode</td>
                                    </tr>
                                    
                                    <tr>
                                    <td>$number</td>
                                    </tr>
                                    <tr><td>This cleaner is $distancetocleaner miles from you!
                                    </td>
                                    </tr>
                                    <tr><td>
                                    Compare:
                                    <input type='checkbox' name='compare[]' value='$id'/>
                                    </td></tr>
                                    </table></center><p>
                                    </font><p>
                                    ";
                                    $count1++;
                                    }}}
                                    

                                    I've tried running the foreach around the final select statement and ending the brackets right at the end of the code, problem is the paid accounts appear more than once in the results
                                    I have put the foreach statement around the whole of my next select statement but I'm getting repeated data where the subscription is PAID for my first IF.

                                    foreach ($sortarray as $key => $val) {	
                                    
                                    }
                                    

                                      My problem is solved now thank godddddddd!!!!!!

                                      Thank you so much everyone for looking at this with me, you really have helped me!

                                      The code now works like so, the second SELECT statement looks to see the id = any of the keys from the first statement:

                                      $directory = "SELECT * FROM directory WHERE id IN ('$key') 
                                      

                                      😃 😃 😃

                                        Write a Reply...