php,在一个foreach中打印一个数组并在另一个foreach中打印一个数组,然后在第一个foreach中打印一个数组,依此类推?

时间:2015-05-13 19:30:40

标签: php loops foreach

我有两个foreach循环:一个是购买信息,另一个是销售信息。

我想要像这样打印,这里有一个foreach循环将包含许多商品供购买,另一个foreach循环将包含许多商品用于销售。我想在购买中循环一个项目,在销售中循环一个项目,依此类推......

任何人都可以建议我怎么做

//purchase infos
foreach($purchase_array as $row){
   echo "<tr>";
        echo "<td>purchase</td>";
        echo "<td>".$row['quantity']."</td>";
        echo "<td>".$row['total']."</td>";
      //if one item finished here it has to go to $sales_array foreach loop and come back to this loop after echoing one item there. so that it can be one row
}
foreach($sales_array as $row){
//sales infos
        echo "<td>sales</td>";
        echo "<td>".$row['bill_number']."</td>";
        echo "<td>".$row['quantity']."</td>";
        echo "<td>".$row['total']."</td>";
    echo "</tr>";
}

2 个答案:

答案 0 :(得分:1)

我猜你需要为所有项目循环并打印一行,所以如果是这种情况你可以试试像这样的嵌套循环

//purchase infos
foreach($purchase_array as $row){
      echo "<tr>";
        echo "<td>purchase</td>";
        echo "<td>".$row['quantity']."</td>";
        echo "<td>".$row['total']."</td>";

        //if one item finished here it has to go to $sales_array foreach loop and come back to this loop after echoing one item there. so that it can be one row
    foreach($sales_array as $row){
        //sales infos
        echo "<td>sales</td>";
        echo "<td>".$row['bill_number']."</td>";
        echo "<td>".$row['quantity']."</td>";
        echo "<td>".$row['total']."</td>";    
    }

    echo "</tr>";
}

答案 1 :(得分:1)

如果您提前计划让他们拥有相同的密钥,您可以这样做:

foreach (array_keys($purchase_array) as $index) {
    echo "<tr>";
    echo "<td>purchase</td>";
    echo "<td>".$purchase_array[$index]['quantity']."</td>";
    echo "<td>".$purchase_array[$index]['total']."</td>";
    echo "<td>sales</td>";
    echo "<td>".$sales_array[$index]['bill_number']."</td>";
    echo "<td>".$sales_array[$index]['quantity']."</td>";
    echo "<td>".$sales_array[$index]['total']."</td>";
    echo "</tr>";
}