Search code examples
phphtmlarraystabular

Elegant way to make a column based array row based


I currently have a array where each field contains another array with the actual data I want to display. This array is column based, meaning each field is one column.

As far as I can tell, to render that data in html I would need to flip it so that it is row based meaning I would need to go through each field and each item of the array in that field and generate a new array where now each item would be a row.

I am wondering if there is a cleaner and more elegant solution than having two nested for loops. Here is some sample data:

$data = array(
    'ID1' => array('Column 1', 'Cell 1', 'Cell 2', 'Cell3')
    'ID2' => array('Column 2', 'Cell 1', 'Cell 2', 'Cell3'),    
    'ID3' => array('Column 3', 'Cell 1', 'Cell 2'),    
);

The final goal is to produce a HTML table (probably using divs rather than table/tr/td)


Solution

  • I don't know of any built in method but you can easily flip an array like this.
    I first find the max number of columns then loop the array with index in a for loop and use that in array_column.
    I also omit 'column' in this code.
    I suppose you don't need that.
    If you do need it change the for loop to start at 0.

    //Find lenghts of columns
    Foreach($data as $column){
        $count[] = count($column);
    }
    $count = max($count);// get the max number of columns
    
    For($i=1;$i<$count;$i++){
        $arr["row" . $i] = array_column($data, $i);
    }
    
    Var_dump($arr);
    

    You can try it here, I use other cell names just to make sure I see that it does correct.

    https://3v4l.org/vEu4r