开发者

check if value is the same in while loop

I'm converting a csv file to xml using the following function:

I want to repeat the same action if $records[$row] value is the same as the previous time that it looped through. How can I accomplish this?

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
  $num = count($data);
  $records[] = $data;

  $stringData .= '<PayTo PTPayeeID="' . $records[$row][2];

  // if the value of $records[$row][2] is the same I want to repeat an action.
  echo "<div id=\"row\"><div id=\"num\">" .$row. "</div>";
  $row++;

  for ($c=0; $c < $num; $c++) {
     if ($c != 1) {
       echo 开发者_如何学Python"<div class=\"field\">" . $data[$c] . "</div>";
     }
  }
}


In general, to compare a row with the previous one, store the previous row's value in a variable. Make sure to assign the variable with a value that won't occur as a real value in your data.

$prevValue = NULL;
while(condition) {
 if ($curValue == $prevValue) {
  .
  . do stuff
  .
 }
 $prevValue = $curValue;
}


Before the while loop do:

$prevRow2 = '';

Then you can compare:

if ($records[$row][2] == $prevRow2) {
    // it's the same as the last time!
}

After using $records[$row][2], simply copy it to $prevRow2 before continuing the while loop.

(If it's possible that $records[$row][2] can be an empty string and you don't want it to match the first iteration, create a $firstTime boolean to check for this.)


if (count($records)>1&&$records[count($records)-1]===$records[count($records)-2]) {
  //do something
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜