Rob
Rob

Reputation: 125

PHP table appearance

I wrote some code to display a html table with PHP. It reads data from a file and checks whether the value is true or false.

The problem is the ugly appearance of the table at the end of the function:

True   False
blue
       Red
       Red
blue

I would like to display the table like this:

True   False
blue   Red
blue   Red

Also it displays the outcome before the function is finished c.q flush(); Here is the code:

?>
<table>
    <tr>
        <th>True</th>
        <th>False</th>
    </tr>
    <?php foreach ($trimmed_array as $value) { ?>
        <tr>
            <?php if (check($value) == 0) { ?>
                <td><?php print $value ?></td>
                <td> </td>
            <?php   
            } else { ?>
                <td> </td>
                <td><?php print $value ?></td>
            <?php
            }
    sleep(1);
    ob_flush();
    flush();
    } ?>
</table>

I realize this code outputs the table like the first example but I can`t seem to figure out how to change it to fit the second example?

Upvotes: 0

Views: 108

Answers (2)

Mihai Matei
Mihai Matei

Reputation: 24276

$true = array();
$false = array();

foreach ($trimmed_array as $value) {
    if (check($value) == 0) {
        $true[] = $value;
    } else {
        $false[] = $value;
    }
}

for ($i = 0; $i < max(count($true), count($false)); $i++) {
    echo '<tr>
        <td>' . (isset($true[$i]) ? $true[$i] : '') . '</td>
        <td>' . (isset($false[$i]) ? $false[$i] : '') . '</td>
    </tr>';
}

Upvotes: 3

andykisaragi
andykisaragi

Reputation: 156

Your code creates one table row per item in the array, so there will always be one blank column per row.

In the 'table' that you would like to display, the items in each row aren't related to each other.

So really you're creating 2 lists here, not a table as such.

I'd do something like this

<?php

$all_values = array('true' => array(), 'false' = array());
foreach($trimmed_array as $value){
  if (check($value) == 0){
    $all_values['true'][] = $value;
  }else{
    $all_values['false'][] = $value;
  }
}

foreach($all_values as $name => $values){
?>

<ul class="<?php print $name;?>">
  <?php 
  foreach($values as $value){
  ?>
    <li><?php print $value; ?></li>
  <?php
  }
  ?>
</ul>

<?php 
}
?>

You can then arrange your lists side by side with CSS

Upvotes: 3

Related Questions