【问题标题】:display array keys as table headers and values in sub arrays as table rows in php?将数组键显示为表头,将子数组中的值显示为php中的表行?
【发布时间】:2022-01-13 02:39:31
【问题描述】:

我有以下数组。如何将数组键显示为标题,将键的值显示为表行。

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
        )

)

我已经显示了这样的数组键标题。

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

如何将值显示为表格行。

【问题讨论】:

  • 所以,表头的array_keys() 是一个好的开始
  • 您希望将哪些值用作表头?从该数组和代码中,您将得到 coa_idaccount_titlebudget1 作为标题。这就是你想要的吗?
  • 你能用纯 html 发布最终结果吗?或者在问题中显示一个简单的表格格式。
  • 我认为您的结构必须更改才能以表格格式打印出来。每个数组都应该有您希望显示的一行,而不是包含一列的所有值。
  • @user663976 是的,这就是我想要的..

标签: php arrays


【解决方案1】:

这里是经过测试的解决方案:

$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>";

【讨论】:

  • 谢谢..它完全符合我的要求....
猜你喜欢
  • 2014-11-05
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 2014-05-07
  • 1970-01-01
  • 1970-01-01
  • 2013-11-14
  • 2017-12-01
相关资源
最近更新 更多