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

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.

  • 写回答

2条回答 默认 最新

  • dqwd71332 2018-10-09 17:30
    关注

    Just store the previous line_id in a variable, and update $i if the value changes. Try the following (explanation in code comments):

    $i = 1;
    $prev_line_id = null; // initializing the previous value
    
    foreach($lineItem as $line) {
    
       // if the previous line_id exists
       if (isset($prev_line_id)) {
    
           // if previous value does not match with the current value
           if ($prev_line_id != $line['line_id']) {
    
               // increment the line number
               $i++;
           }
       }
    
       // set the previous value
       $prev_line_id = $line['line_id'];
    
       echo $i; //line number
       echo $line['field_changed'];
       echo $line['change_date'];
       echo $line['change_from'];
       echo $line['change_to'];
    }
    

    Note that you can get the changing line number directly from DB query itself. You can use window functions like Dense_Rank().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 soildworks装配体的尺寸问题
  • ¥100 有偿寻云闪付SDK转URL技术
  • ¥30 基于信创PC发布的QT应用如何跨用户启动后输入中文
  • ¥20 非root手机,如何精准控制手机流量消耗的大小,如20M
  • ¥15 远程安装一下vasp
  • ¥15 自己做的代码上传图片时,报错
  • ¥15 Lingo线性规划模型怎么搭建
  • ¥15 关于#python#的问题,请各位专家解答!区间型正向化
  • ¥15 unity从3D升级到urp管线,打包ab包后,材质全部变紫色
  • ¥50 comsol温度场仿真无法模拟微米级激光光斑