【问题标题】:Convert array to Horizontal in php在php中将数组转换为水平
【发布时间】:2021-07-05 12:28:26
【问题描述】:

我在 ci3 中有以下结果数组:

array (size=3)
  0 => 
    array (size=2)
      'Months' => string 'January' (length=7)
      'Operations' => string '6' (length=1)
  1 => 
    array (size=2)
      'Months' => string 'February' (length=8)
      'Operations' => string '3' (length=1)
  2 => 
    array (size=2)
      'Months' => string 'March' (length=5)
      'Operations' => string '7' (length=1)

我想以以下水平形式显示上述(或任何派生数组):

Months     January February March
Operations 6       3        7

现在我正在使用以下代码以垂直形式显示表格:

<table>
            <thead>
                <tr>
                    <th>Month</th>
                    <th>Operations</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($months): ?>
                <?php foreach ($months as $result): ?>
                <tr>
                    <td><?php echo $result['Months']; ?></td>
                    <td><?php echo $result['Operations']; ?></td>
                    </td>
                </tr>
                <?php endforeach;?>
                <?php endif;?>
            </tbody>
 </table>

我已使用 array_map 将我的数组转换为这种形式:

$converted = array_map(null, ...$months);

array (size=2)
  0 => 
    array (size=3)
      0 => string 'January' (length=7)
      1 => string 'February' (length=8)
      2 => string 'March' (length=5)
  1 => 
    array (size=3)
      0 => string '6' (length=1)
      1 => string '3' (length=1)
      2 => string '7' (length=1)

但是如何迭代才能得到想要的结果呢?

【问题讨论】:

  • 遍历数组一次,将月份输出到表格单元格中。第二次循环数组,将操作输出到表格单元格中。将每个循环包装成一个tr。响应。使用修改后的数组,首先循环 [0],然后循环 [1]。

标签: php mysql codeigniter


【解决方案1】:

你可以尝试这样的事情(未测试):

<table>

<tbody>

<?php if ($months): ?>
    <tr>
        <td>Months</td>
    <?php foreach ($months as $key => $result): ?>
            <td><?php echo $result['Months']; ?></td>
    <?php endforeach;?>
    </tr>
    <tr>
        <td>Operations</td>
        <?php foreach ($months as $key => $result): ?>
            <td><?php echo $result['Operations']; ?></td>
        <?php endforeach;?>
    </tr>
<?php endif;?>
</tbody>

【讨论】:

  • 谢谢,完美。所以解决方案是用 for each 迭代返回数组的每个子键,不需要转置。我尝试了许多不同的解决方案,但我的头被卡住了。我所做的唯一更改是将第一个 td 转换为几个月的 th 以用作标题。再次感谢!!
  • 是的,我省略了标题部分,因为它们不是“真正的”标题,但这只是语义:D
猜你喜欢
  • 2013-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-30
  • 2015-01-27
  • 1970-01-01
相关资源
最近更新 更多