如何使用while循环合并foreach循环来构建html表?
问题描述:
我有两个数组$ _SESSION ['fff']有数量,另一个是从mysql数据库中提取的结果,包括产品的名称,价格和重量,我需要建立一个包含数据的表从数据库和包括会话变量数组如何使用while循环合并foreach循环来构建html表?
$wherein = implode(",", $_SESSION['cart']);
$sql = "select id, item_name, Price, Weight from items where id IN
($wherein)";
$result= mysqli_query($conn, $sql);
echo "<table style='width:100%' border='1' >";
echo "<tr>";
echo "<th> Product Name</th>";
echo "<th>Product Price </th>" ;
echo "<th>Weight </th>" ;
echo "<th>Quantity </th>" ;
echo "</tr>";
$sum = '';
$s= '';
while (($row = mysqli_fetch_array($result, MYSQLI_ASSOC))) &&
foreach($_SESSION['fff'] as $value){
$sum += $row['Price'];
$s += $row['Weight'];
echo "<tr>";
echo "<td>" . $row['item_name'] . "</td>";
echo "<td> $". $row['Price'] . "</td>" ;
echo "<td>". $row['Weight'] ;
echo "<td>".$value."</td>";
}
我一直在尝试了几个小时,现在网上搜索和尝试不同的方法,但未能得到解决的数量。谢谢。
答
会话值分配给变量像
$session_var = $_SESSION['fff'];
唐`使用的foreach() 声明变量
$i=0;
while(($row = mysqli_fetch_array($result, MYSQLI_ASSOC)))
{
$sum += $row['Price'];
$s += $row['Weight'];
echo "<tr>";
echo "<td>" . $row['item_name'] . "</td>";
echo "<td> $". $row['Price'] . "</td>" ;
echo "<td>". $row['Weight'] ;
echo "<td>".$session_var[$i]."</td>";
$i++;
}
+0
,非常感谢你..... :) – hossam
答
你能做到像这样:
for($i = 0; $row = mysqli_fetch_array($result, MYSQLI_ASSOC); $i++) {
// access rows using $row
// access corresponding session data using $_SESSION['fff'][$i]
}
如果你的$ _SESSION ['fff']中的数组键不是数字,请在循环前添加以下内容:
$session = array_values($_SESSION['fff']);
然后在循环中使用$session[$i]
访问值。
您不能像这样“合并”这些循环,如果您发现需要这样的话,那么您的逻辑有些问题。你能描述一下它应该如何工作,这样我们才能找到解决方案? – Enstage
我有两个数组$ _SESSION ['fff']有数量,另一个是从mysql数据库中提取的结果,包括产品名称,价格和重量,我需要建立一个表,其中包含数据数据库和会话变量数组中包含的数量 – hossam
$ _SESSION ['fff']中的数据如何链接到结果集中的数据? – Enstage