display array keys as table headers and values in sub arrays as table rows in php?

0

Issue

i have the following array. how to display array keys as headers and values of keys which are also arrays as table rows.

Array
(
    [coa_id] => Array
        (
            [0] => 3012
            [1] => 3013
            [2] => 3014
            [3] => 3015
            [4] => 3016
            [5] => 3017
            [6] => 3018
            [7] => 3019
            [8] => 3020
            [9] => 3021
            [10] => 3022
            [11] => 3023
            [12] => 3024
        )

    [account_title] => Array
        (
            [0] => Pay of Officers and Official
            [1] => Fixed Pay Contract Employees
            [2] => Leave Salary
            [3] => GP Fund Payments
            [4] => Postage and Telegraph
            [5] => Telephone Bill
            [6] => Electric Bill and Electric Appliances
            [7] => Hot and Cold Weather Charges
            [8] => Travelling Allowance
            [9] => Transportation Charges
            [10] => POL Charges
            [11] => CP Fund Payable
            [12] => CP Fund Payments
        )

    [budget] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
            [3] => 0
            [4] => 0
            [5] => 0
            [6] => 0
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
            [12] => 0
        )

    [1] => Array
        (
            [3012] => 0
            [3013] => 0
            [3014] => 0
            [3015] => 0
            [3016] => 0
            [3017] => 0
            [3018] => 0
            [3019] => 0
            [3020] => 0
            [3021] => 0
            [3022] => 0
            [3023] => 0
            [3024] => 0
        )

)

i have displayed array keys headers like this.

enter code here foreach ($exp as $key => $value) {
 echo '<th>'. $key .'</th>';
} 

how to display the values as table rows.

Solution

here is tested solution:

$th = array();
$td = array();
$col_cnt = 0;
foreach ($exp as $key => $value) {
    $th[] = "<th>{$key}</th>";
    foreach ($value as $val) {
        $td[$col_cnt][] = $val;
    }
    $col_cnt++;
}
print "<table><thead>".implode("", $th)."</thead><tbody>";
for ($i=0; $i<count($td[0]); $i++) {
    print "<tr>";
    for ($j=0; $j<$col_cnt; $j++) {
        print "<td>{$td[$j][$i]}</td>";
    }
    print "</tr>";
}
print "</tbody></table>";

Answered By – diavolic

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More