Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2003
    Posts
    61

    Unanswered: this problem is killing me!!!

    Hey everyone. For my own sanity, I need to know how to do this.

    I have a table with numbers in MYSQL

    I can do:
    <table>
    <?php
    $sql = mysql_query("select mynumber from `table` order by mynumber");
    while ($myrow = mysql_fetch_array($sql)) {
    extract($myrow);
    echo '<tr><td>'. $mynumber .'</td></tr>
    }
    ?>
    </table>
    (i get)
    1
    2
    3
    4
    5
    6
    7
    ... etc...


    but what if I want it in 4 columns - sorted vertically?


    1 5 9 13
    2 6 10 14
    3 7 11 15
    4 8 12 16


    to get it to sort horizontally - no problem, I can do it. But I need to know how to do it vertically and handle uneven number of total records pulled from the database, for example - 10

    1 4 7 10
    2 5 8
    3 6 9


    I've been trying with arrays for about 8 hours now and got it close, but records, 14 records are just not displaying properly and I'm very weak with arrays anyway.

    Any idea?
    Thanks

  2. #2
    Join Date
    Nov 2004
    Location
    out on a limb
    Posts
    13,692
    Provided Answers: 59
    you may be able to do it easily using CSS

    OR

    failing that as you have already identified you could stick 'em into an array with the appropriate sort key

    you can easily find the number of values returned with the (I think mysql_norowsaffected function or similar

    so you cold then work out the number of rows and columns to display
    retrieve your data fromt he db and place it into an array

    Key | Value
    1 | 1 'key could be R01C01, R01C02 or whatever
    2 | 4
    3 | 7
    4 | 10
    5 | 2
    6 | 5
    7 | 8
    8 |
    9 | 3
    10 | 6
    11 | 9

    then extract in key sorted order an put into a table
    I'd rather be riding on the Tiger 800 or the Norton

  3. #3
    Join Date
    Mar 2007
    Location
    636f6d7075746572
    Posts
    770
    A solution close to what you're looking for : (requires PHP5)


    Code:
    $arr = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14);
    
    // Num of Columns you want output.
    $numOfCols = 5;
    $numOfRows = ceil((count($arr)/$numOfCols));
    
    $arr = array_chunk($arr,$numOfRows);
    
    for($i=0;$i<$numOfRows;$i++){
    	foreach($arr as $key=>$value){
    		if(isset($value[$i])){
    			echo $value[$i].",";
    		}
    	}
    	echo "<br>";
    }
    Edit : Problem with undefined indexes fixed.
    Last edited by aschk; 04-18-07 at 10:43.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •