2

I have an array like this:-

$str = array(
    array(
        'amount' => 1.87,
        'user' => 'hello',
    ),
    array(
        'amount' => 0.9,
        'user' => 'test',
    ),
    array(
        'amount' => 9,
        'user' => 'hello',
    ),
    array(
        'amount' => 1.4,
        'user' => 'test',
    )
);

Now I show this data in HTML table like this for user 'test' :-

<thead>
    <tr>
        <th>Amount</th>
        <th>User</th>
</thead>
<tbody>
    <tr>
        <td><?php
            foreach ($str as $new_str) {
                if ($new_str['user'] == "test") {
                    echo $new_str['amount'];
                    echo "<br />";
                }
            }

            ?></td><td><?php
            foreach ($str as $new_str) {
                if ($new_str['user'] == "test") {
                    echo $new_str['user'];
                    echo "<br />";
                }
            }
            ?></td>
    </tr>
</tbody>

But now the problem is that when I use this code it shows the amount and user as a whole instead of two different rows. How can I fix this? Any help?

2 Answers 2

3

You just need to move your foreach loop outside of the <tr>...</tr> structure. This should work:

<?php foreach($str as $new_str){
    if($new_str['user']=="test"){
        echo "<tr><td>" . $new_str['amount'] . "</td><td>" . $new_str['user'] . "</td></tr>";
    }
}
?>

Output (for your data)

<tr><td>0.9</td><td>test</td></tr>
<tr><td>1.4</td><td>test</td></tr>
Sign up to request clarification or add additional context in comments.

1 Comment

Rats! You beat me by seconds! Cheers!
2

Your tr was not repeating. output image I hope this will help.

    <?php
       $str = array(
            array(
                'amount' => 1.87,
                'user' => 'hello',
            ),
            array(
                'amount' => 0.9,
                'user' => 'test' ,
            ),
            array(
                'amount' => 9,
                'user' => 'hello',
            ),
            array(
                'amount' => 1.4,
                'user' => 'test',
            )
);
?>
<table>
    <thead>
            <tr>
                <th>Amount</th>
                <th>User</th>
            </tr>
    </thead>
    <tbody>
                <?php foreach($str as $new_str) {
                    if($new_str['user'] == "test"){
                        echo '<tr>';
                        echo '<td>'.$new_str['amount'].'</td>';
                        echo '<td>'.$new_str['user'].'</td>';
                        echo '</tr>';
                    }
                } ?>

    </tbody>
</table>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.