loliki
loliki

Reputation: 957

PHP Foreach inside foreach display data in table row

How can I display data in a tablerow inside a foreach function? The agenda variable works fine, the rows variable is the one making problems, I need it inside a tag

<?php
$agenda = $days = json_decode(get_field( "field_uc_content_json" ));
unset($agenda[0]); ?>



<table class="table">
    <thead>
        <tr>
          <th> Day </th>
          <th>Description</th>
          <th>Hours</th>
        </tr>
    </thead>
<tbody>
   <?php foreach($agenda as $column) { ?>
   <tr>
    <td><?php echo $column[0]; ?></td>
    <td><?php
    $rows = explode( "\n", $column[1]);
    foreach ($rows as $row) { ?>
    <tr> <?php echo $row; ?> </tr>
    <?php    } ?>
   </td>
</tbody>
</table>

The second foreach

vardump agenda

enter image description here

vardump rows

enter image description here

Upvotes: 1

Views: 7070

Answers (3)

Ronnie Oosting
Ronnie Oosting

Reputation: 1252

This will do it:

<tbody>
<?php foreach($agenda as $column):
    $rows = explode("\n", $column[1]);?>
    <tr>
        <td rowspan="<?php count($rows) + 1?>"><?php $column[0];?></td>
    </tr>

    <?php foreach($rows as $row): ?>
        <tr>
            <td><?php echo $row ;?></td>
            <td><?php echo $row ;?></td>
        </tr>
    <?php endforeach;

endforeach; ?>
</tbody>

As we (and icecub) discussed in the chatroom.

Good luck friend.

Upvotes: 3

acuedd
acuedd

Reputation: 31

It because you variable

$agenda = $days = json_decode(get_field( "field_uc_content_json" ));
unset($agenda[0]); ?>

it's a object and this you dont use like a array, you need manage like object in the explode, like this:

$rows = explode( "\n", $column->1);

Upvotes: 1

pedram shabani
pedram shabani

Reputation: 1680

I think it is work fine now.I tested it.

<table class="table">
    <thead>
        <tr style="background: #8da80c;">
          <th> Day </th>
          <th>Description</th>
          <th>Hours</th>
        </tr>
    </thead>
<tbody>
   <?php foreach($agenda as $column) { ?>
   <tr style="background: #e0e545;">
    <td style="padding: 14px;"><?php echo $column[0]; ?></td>
    <td style="padding: 14px;"><?php echo $column[1]; ?></td>
     <td style="padding: 14px;"><?php echo $column[2]; ?></td>
   </tr>
   <?php } ?>
</tbody>
</table>

I tested with these values

  <pre>
<?php
$agenda = array (array("montag","Lorem ipsum dolor sit amet","08:00"),array("montag","Lorem ipsum dolor sit amet","08:00"),array("montag","Lorem ipsum dolor sit amet","08:00"));

print_r($agenda);
?>
     </pre>

Upvotes: 2

Related Questions