简体   繁体   English

PHP中的foreach循环中的while循环

[英]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_a 3
name_b 5 name_b 5
name_c 2 name_c 2
name_d 4 name_d 4
name_e 1 name_e 1

thank you in advance. 先感谢您。

You don't need that foreach loop. 您不需要那个foreach循环。 Simply use array_shift() function inside while() loop to get each array element. 只需在while()循环内使用array_shift()函数即可获取每个数组元素。 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. 如果不是这种情况,则需要在查询中使用LIMIT子句。


Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. 旁注:不要使用mysql_*函数,从PHP 5.5开始不推荐使用它们,并在PHP 7.0中将其完全删除。 Use mysqli or pdo instead. 改用mysqlipdo And this is why you shouldn't use mysql_* functions . 这就是为什么您不应该使用mysql_*函数的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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