Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 重新启动While循环_Php_Mysql_Foreach_While Loop - Fatal编程技术网

Php 重新启动While循环

Php 重新启动While循环,php,mysql,foreach,while-loop,Php,Mysql,Foreach,While Loop,是否可以重新启动while循环?我目前在foreach循环中有一个while循环,每次都需要while语句从头开始 $sql = mysqli_query($link, "SELECT * FROM products"); $products = array('Milk', 'Cheese', 'Eggs'); $i = 0; $total = count($products); //This is in case I change the product list. if($sql) {

是否可以重新启动while循环?我目前在foreach循环中有一个while循环,每次都需要while语句从头开始

$sql = mysqli_query($link, "SELECT * FROM products");
$products = array('Milk', 'Cheese', 'Eggs');
$i = 0;
$total = count($products); //This is in case I change the product list.

if($sql)
{
    foreach($products as $v)
    {
        while($r = mysqli_fetch_assoc($sql))
        {
            if($r['Name'] == $v)
            {
                echo $r['Name'] . " - £" . $r['Price'];
                break;
            }
        }
    }
}
我的问题发生在代码运行时,它会产生
牛奶
鸡蛋
,但在数据库中
奶酪
出现在
鸡蛋
之前,因此它似乎永远找不到。如何重新启动while循环,以强制代码从sql查询开始检查每个值


已解决:使用哈希来查询,而不是循环sql。

我认为最好的办法是将查询结果存储在哈希中,以便进行O(1)查找,而不是反复读取sql

$sql = mysqli_query($link, "SELECT * FROM products");
$sql_products = array();
$products = array('Milk', 'Cheese', 'Eggs');
$i = 0;
$total = count($products); //This is in case I change the product list.

if($sql)
{
    while($r = mysqli_fetch_assoc($sql))
    {
        $sql_products[$r['Name']] = $r;
    }
    foreach($products as $v)
    {
        if(array_key_exists($v,$sql_products))
        {
            echo $v . " - £" . $sql_products[$v]['Price'];
        }
    }
}

为什么要重新启动while循环,首先将所有数据提取到一个数组中,然后像正常的内部循环那样执行呢loops@MansoorkhanCherupuzha我从未将数据提取到数组中?我假设运行一个while循环,然后在其中运行一个foreach($row),这就是你的意思?我假设这与@MansoorkhanCherupuzha所说的有点类似?似乎正在将其存储在阵列中?是的,类似。但是使用散列而不是数组,所以查找速度要快得多。@MikeShaw,是的,这就是我的意思。太棒了,很有魅力,谢谢大家!在php.net上有没有一个页面或任何你可以链接到我的东西,这样我就可以了解更多关于哈希的信息?