table columns function

Discussion in 'PHP' started by zkvision, Sep 22, 2008.

  1. #1
    Hello Everybody,
    Needs help in generating output for the following function.

    thanks
    
    function tcolumns($input, $cols) {
    $input = array('one', 'two', 'three', 'four', 'five', 'six', 'seven');
        $cols = 2;
         /* 
    $output = should be like this
    <table><tr>
        <td>one</td>
        <td>five</td>
    </tr><tr>
        <td>two</td>
        <td>six</td>
    </tr><tr>
        <td>three</td>
        <td>seven</td>
    </tr><tr>    
       <td>four</td>
        <td></td>
    </tr> </table>
        */ 
        return $output;
    } 
    
    PHP:

     
    zkvision, Sep 22, 2008 IP
  2. ads2help

    ads2help Peon

    Messages:
    2,142
    Likes Received:
    67
    Best Answers:
    1
    Trophy Points:
    0
    #2
    someone might have better way but at least the function below can do it
    
    function tcolumns($input, $cols) {
    $output = "<table>";
    $number_of_tr = round(count($input)/$cols);
    
    for ($i=0;$i<=($number_of_tr-1);$i++) {
    $output .="<tr>\r\n";
        for ($ii=1;$ii<=$cols;$ii++) {
        if (!isset($pointer)) { $pointer = $i; } else { $pointer = $i+4; }
        $output .= "  <td>".$input[$pointer]."</td>\r\n";
        }
        /* reset $pointer */ unset($pointer);
        $output .= "</tr>\r\n";
    }
    $output .= '</table>';
    return $output;
    }
    
    PHP:
    Test the function using this
    
    // i dont know if this matters but please assign key 0 to the first item in the array if you can
    $input = array( 0=> 'one', 'two', 'three', 'four', 'five', 'six', 'seven');
    $cols = 2;
    print tcolumns($input,$cols);
    
    PHP:
    try to assign key 0 to the first item in the array because the key is important for the function to run properly
    i do not know if this matters.
    hope this helps
     
    ads2help, Sep 23, 2008 IP