Using queried results in a seperate query Order by

Discussion in 'PHP' started by rtblizz, Mar 22, 2012.

  1. #1
    I am taking results ($result2) that I get from a one query and formatting them in a way to be inserted in another query. This works fine using the code below

    
    
    //take results and customize them for query value insert
    
    while ($row = mysql_fetch_array($result2, MYSQL_ASSOC))
        {
            $strquery .= " ".$row["zipcode"].", ";
        }
    
    //take list and stop the , at end of query insert
    
        $strquery = rtrim($strquery, ', ');
    
    
    PHP:
    doing this above it gives me these result: 21146, 21032, 21123, 21144

    then I insert them here and it works great.

    
    
    $query = "select * from Table where ZipCode IN (".$strquery.") order by Value";
    
    
    PHP:
    that's where my question comes in I would like to order by the results and Value??

    My results currently display zip codes in ascending order like this. (21032, 21123, 21144, 21146) low to high

    How can I get the query to display results in the results order above. (21146, 21032, 21123, 21144)

    My thought was something like this but it breaks when I use it..

    
    
    $query = "select * from Table where ZipCode IN (".$strquery.") order by Value, ZipCode [(".$strquery.")]";
    
    
    PHP:
    any help would be appreciated :)
     
    rtblizz, Mar 22, 2012 IP
  2. zacharooni

    zacharooni Well-Known Member

    Messages:
    346
    Likes Received:
    20
    Best Answers:
    4
    Trophy Points:
    120
    #2
    You might have to buffer your results into an associative array, and use:

    $zip_array = array();
    while ($row = mysql_fetch_array($result2, MYSQL_ASSOC))
    {
      $zip_array[ $row['zipcode'] ] = $row['value'];
      /* You could also do $zip_array[ $row['zipcode'] ] = $row; then store all of the columns in the value portion of the associative array */
      $strquery .= " ".$row["zipcode"].", ";
    }
    print_r($zip_array);
    
    /*
    
    For key=>val arrays, if you want it back in ascending order
    
    By value:
    $new_zip_array = asort($zip_array);
    By key:
    $new_zip_array = ksort($zip_array);
    
    */
    
    PHP:
     
    zacharooni, Mar 22, 2012 IP