douxie9347
2018-10-09 17:08
浏览 419
已采纳

PHP:根据foreach循环中另一个变量的变化增加变量

I have a foreach loop that prints the history of line item changes in my application. Each line item has a number, and each line item can have multiple changes.

What I want to do is display the line number alongside each change when my loop executes. $i will hold the line number.

$i = 1;
foreach($lineItem as $line) {
   echo $i; //line number
   echo $line['field_changed'];
   echo $line['change_date'];
   echo $line['change_from'];
   echo $line['change_to'];
}

The code reads from a DB table called line_item_changes with the following structure:

id  line_id  parent_id
--  -------  ---------
1   2401     521
2   2401     521
3   2401     521
4   2500     521
5   2502     521
6   2502     521  

I want to increment $i every time the value in $line['line_id'] changes. So that, when the results display, they look something like this:

Line #: 1
field: notes
date: 10/9/2018
from: test
to: test2

Line #: 1
field: quantity
date: 10/1/2018
from: 4
to: 3

Line #: 2
field: need_date
date: 10/1/2018
from: 10/24/2018
to: 10/27/2018

etc.

图片转代码服务由CSDN问答提供 功能建议

我有一个foreach循环,用于打印应用程序中订单项更改的历史记录。 每个订单项都有一个数字,每个订单项都可以有多处更改。

我想要做的是在循环执行时显示每个更改旁边的行号。 $ i 将保留行号。

  $ i = 1; 
foreach($ lineItem as $ line){
 echo $ i;  //行号
 echo $ line ['field_changed']; 
 echo $ line ['change_date']; 
 echo $ line ['change_from']; 
 echo $ line ['change_to']; 
  } 
   
 
 

代码从名为 line_item_changes 的数据库表中读取,结构如下:

   id line_id parent_id 
-- ------- --------- 
1 2401 521 
2 2401 521 
3 2401 521 
4 2500 521 
5 2502 521 
6 2502 521  
   
 
 

每当 $ line ['line_id'] 中的值发生变化时,我想增加 $ i 。 因此,当结果显示时,它们看起来像这样:

  Line#:1 
field:notes 
date:10/9/2018 
 from:test 
to  :test2 
 
Line#:1 
field:quantity 
date:10/1/2018 
 from:4 
to:3 
 
Line#:2 
field:need_date 
date:10/1/2018 
from  :10/24/2018 
to:10/27/2018 
   
 
 

等。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题