Convert array to Horizontal in php

I have the following result array in 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)

I want to display the above (or any derived array) in the following horizontal form:

Months     January February March
Operations 6       3        7

Right now I’m using the following code to display the table in Vertical form :

<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>

I have converted my array to this form using 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)

But how to iterate in order to get the desired result ?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You could try something like this (not tested):

<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>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x