简体   繁体   中英

Uncaught Error: Call to undefined function each()

I'm wondering if you guys can give me an idea about how to replace this each function:

while(list($key,$val) = each($_SESSION['cart'][$i]))
        {
            if ($key=="product_name"){
                $product_name=$val;
            }else if($key=="units"){
                $units=$val;
            }else if($key=="packing_size"){
                $packing_size=$val;
            }else if($key=="grade"){
                $grade=$val;
            }else if($key=="length"){
                $length=$val;
            }else if($key=="quantity"){
                $quantity=$val;
            }
        }
        echo $product_name."".$units."".$packing_size."".$grade."".$length."".$quantity;
        echo "<br>";
    }

Thanks!

I've try to use foreach, but isn't working at all

I assume your original question is "How to replace a deprecated loop with each()"...?
In this case ADyson's commentary will be of great help to you.

But then why carry out tests on keys to obtain values that you then place in variables that you only display...?
If you just want to display the values you can access your array through the keys
As in the code below

foreach($_SESSION['cart'][$i] as $key => $val)
{
    echo $val["product_name"]."".$val["units"]."".$val["packing_size"]."".$val["grade"]."".$val["length"]."".$val["quantity"];
    echo "<br>";    
}

for a more elegant solution and better optimisation you can use foreach and a switch statement

foreach ($_SESSION['cart'][$i] as $key => $val) {
    switch ($key) {
        case "product_name":
            $product_name = $val;
            break;
        case "units":
            $units = $val;
            break;
        case "packing_size":
            $packing_size = $val;
            break;
        case "grade":
            $grade = $val;
            break;
        case "length":
            $length = $val;
            break;
        case "quantity":
            $quantity = $val;
            break;
    }
}
echo $product_name . "" . $units . "" . $packing_size . "" . $grade . "" . $length . "" . $quantity;
echo "<be>";

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