简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM