Search code examples
phparraysforeachhtml-tablesimple-html-dom

Create columns in PHP


I have some values in array like this:

$elm = 'a,b,c';
$elm2 = 'd,e,f';

I would like to create a table out of this data which would look like this:

table:
a d
b e
c f

It seems impossible, since HTML tables are created horizontally, I'm always somehow getting this:

table:
a b c
d e f 

I tried many things for instance:

echo '<table>';

 foreach($html->find($elm) as $m){
   echo '<tr><td>' . $m . '</td>'; 

 foreach($html->find($elm2) as $m2){
        echo '<td>' . $m2 . '</td>';
    }

echo '</tr>';
}

echo '</table>';

Which gives me this:

table:
a d e f
b d e f
c d e f 

So the first column is correct but the other ones are spread out horizontally and duplicated.


Solution

  • Some magic:

    $array = [explode(',',$elm), explode(',',$elm2)];
    $array = call_user_func_array('array_map', array_merge([NULL], $array));
    
    foreach ($array as $sub) {
        echo implode(' ', $sub) . "\n";
    }
    

    Output:

    a d
    b e
    c f
    

    Demo