【问题标题】:php, print one array in one foreach and print one array in another foreach, then print an array in first foreach and so on, how to?php,在一个foreach中打印一个数组,在另一个foreach中打印一个数组,然后在第一个foreach中打印一个数组,依此类推,怎么做?
【发布时间】:2015-05-13 19:30:39
【问题描述】:

我有两个 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>";
}

【问题讨论】:

标签: php loops foreach


【解决方案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 1:n 吗?我认为可以进行 2 个或 3 个嵌套循环,但对于您的情况,这似乎是一种不好的做法。为什么不在返回所有值之前使用内部连接或其他东西进行 sql 查询。这样你就只能使用一个 foreach。有可能吗?
  • 我已经进行了 switch case 检查 1) 两个数组计数都等于 1,2) n:1 3) 1:n,我现在解决了以上所有问题,只有这个待定。也许这是一种不好的做法,因为我是新人。
  • 我认为您需要澄清您的问题。如果您对以上所有内容都满意,那么问题是什么?
  • “我遇到了一种情况,如果购买信息数组只有一个值而销售数组有更多值怎么办”。如果 $purchase_array 有一个值并且 sales 更多,那么您将获得更多 td 列,这些列指的是第一个旁边的特定销售。不确定这是否是个好主意。如果您每次购买的销售额更多,而我认为这在逻辑上是不可能的,那么您应该制作一个只显示购买的表格,当您单击一项购买时,我会显示销售额。
【解决方案2】:

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

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>";
}

【讨论】:

    猜你喜欢
    • 2012-01-05
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多