PHP two dimensional array into HTML

后端 未结 3 619
逝去的感伤
逝去的感伤 2020-12-15 01:36

A simple Google search will reveal a multitude of solutions for converting a two dimension array into HTML using PHP. Unfortunately none of these has the answers I am lookin

3条回答
  •  臣服心动
    2020-12-15 02:14

    You'll need two loops. One to loop through the first level, and another to go through the second level. This assumes that your two dimensional array is regularly rectangular.

    //our example array
    $foo['one']['a'] = '1a';
    $foo['one']['b'] = '1b';
    $foo['two']['a'] = '2a';
    $foo['two']['b'] = '1b';
    
    //open table
    echo '';
    
    //our control variable
    $first = true;
    
    foreach($foo as $key1 => $val1) {
        //if first time through, we need a header row
        if($first){
            echo '';
            foreach($val1 as $key2 => $value2){
                echo '';
            }
            echo '';
    
            //set control to false
            $first = false;
        }
    
        //echo out each object in the table
        echo '';
        foreach($val1 as $key2 => $value2){
            echo '';
        }
        echo '';
    }
    
    echo '
    '.$key2.'
    '.$key1.''.$value2.'
    ';

    Haven't tested it, but that should do it for you. First level of the array is rows, second level of the array is columns.

    Sample Output for our $foo array:

    +-----+-----+-----+
    |     |  a  |  b  |
    +-----+-----+-----+
    | one | 1a  | 1b  |
    +-----+-----+-----+
    | two | 2a  | 2b  |
    +-----+-----+-----+
    

提交回复
热议问题