ゆにた どうえ
ゆにた どうえ

Reputation: 93

while loop inside foreach loop in PHP

i want to make a table that on the first column consist of name from database and on the second column consist of value from an array. this is what i have

<table>
    <tr> 
        <?php $arr=array(3,5,2,4,1);                            
        $name= mysql_query("SELECT name FROM table")
        foreach ($arr as $rs){                          
            while($n=mysql_fetch_array($name)){ ?>                      
                <td><?=$n['name']?></td>
                <td><?=$rs?></td>
    </tr>
    <?php   }   }   ?>                          
</table>

i need an output like

name_a 3
name_b 5
name_c 2
name_d 4
name_e 1

thank you in advance.

Upvotes: 0

Views: 1245

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

You don't need that foreach loop. Simply use array_shift() function inside while() loop to get each array element. So your code should be like this:

<table>
    <tr> 
    <?php 
        $arr=array(3,5,2,4,1);                            
        $name= mysql_query("SELECT name FROM table")                        
        while($n=mysql_fetch_array($name)){ 
            $rs = array_shift($arr); 
    ?>                      
            <td><?=$n['name']?></td>
            <td><?=$rs?></td>
    </tr>
    <?php   
        }      
    ?>                          
</table>

Furthermore, your business logic work will work only if the number of the rows in the table equals to the number of elements in the array. And if it's not the case then you need to use LIMIT clause in your query.


Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.

Upvotes: 2

Related Questions