Skip to content
Advertisement

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

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.

Advertisement

Answer

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>";
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement