2015-12-30 127 views
-3

编辑回答下面的代码,这一个完美的工作。 ♥新年快乐,大家好♥PHP错误的foreach代码

$custom = "8-1,1-1,4-1,"; 

$product_id_string = $_POST['custom']; 
$product_id_string = rtrim($product_id_string, ","); 
$id_str_array = explode(",", $product_id_string); 
foreach ($id_str_array as $key => $value) { 

$id_quantity_pair = explode("-", $value); // Uses Hyphen(-) as delimiter to separate product ID from its quantity 
$id = $id_quantity_pair[0]; // Get the product ID 
$product_quantity = $id_quantity_pair[1]; // Get the quantity 
$sql = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1"); 
while ($row = mysql_fetch_array($sql)) { 
    $product_name = $row["product_name"]; 
    $product_price = $row["price"]; 
} 
$product_price = $product_price * $product_quantity; 
$message2 .= "<tr>"; 
$message2 .= "<td style='text-align:center'>" . $product_name . "</td>"; 
$message2 .= "<td style='text-align:center'>" . $product_quantity . "</td>"; 
$message2 .= "<td style='text-align:center'>" . $product_price . " €</td>"; 
$message2 .= "</tr>"; 
} 

代码编辑,工作完美:)

+7

1)'定制= '8-1,1-1,4-1';'是错误的(缺少'$')。 2)你用'foreach'迭代一个字符串,期望这些元素是关联数组3)你以不安全的方式使用mysql_query'并且不推荐使用该扩展 –

+0

显示你实际的'$ custom'变量。 –

回答

0

第一线,自定义不是一个变量(可以复制和粘贴错误)

$custom 

然后你目前所使用的数组运算符分割字符串,则需要先拆分该字符串使用:

$custompieces = explode(",", $custom); 

然后,您已将$ custom声明为$ each_item,但您似乎试图访问不存在的子数组。 $ each_item [id]和$ each_item [数量]没有在任何地方定义。我猜测你正试图将8-1分成id-quantity,在这种情况下,你需要实际定义那些能够使用它们的。

$pieces = explode("-", $each_item); 
$id = $pieces[0]; 
$quantity = $pieces[1]; 

因此,最终的代码需要:

$custom = "8-1,1-1,4-1,"; 
$custompieces = explode(",", $custom); 
foreach ($custompieces as $each_item) { 
$pieces = explode("-", $each_item); 
$id = $pieces[0]; 
$quantity = $pieces[1]; 
$sql3 = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1"); 
while ($row = mysql_fetch_array($sql3)) { 
    $product_name = $row["product_name"]; 
    $price = $row["price"]; 
} } 
+0

很好的答案,但它只打印出字符串中的最后一条记录。 – BeeBee

+0

它会这样做,因为您正在覆盖每行上的输出。把你的动作放在函数 –

+0

里面,看。我已经把这个动作放在这个函数里面了,它现在将最后一个记录的名字和价格翻倍,但是数量是空的。我怎么解决这个问题? – BeeBee

0

foreach旨在用于遍历array但你使用它与一个string

所以它不适合你。