0

我正在尝试将一些信息从数据库流入 HTML 以显示给我的用户。每次“行业”发生变化时,我都想打印新标签。我正在尝试使用一个名为 $last_industry 的变量来跟踪我当前迭代的行业是否等于最后一个,但我没有得到好的结果。我在下面粘贴了我的代码。$c['user_industries_title'] 是我需要监控的。

$last_industry = 'foo';

foreach($case_studies as &$c) {
  //If the last industry we iterated over is different than the one we're currently iterating over, close the last section and print a new section.
  if($last_industry != $c['user_industries_title']){
    echo "</section>"  
    echo "<section>";
    $changed = 1;
  }else {$changed = 0}

  $c = $last_industry;
  $last_industry = $c['user_industries_title'];
}

此问题与 $last_industry 变量有关。为此,它需要将自身更新为最新的 $c['user_industries_title'] 以便在下一次迭代开始时重新使用,这不会发生。我错过了什么吗?

4

2 回答 2

2

当值发生变化时,您需要更改 if() 中的 $last_industry 值,否则您始终以相同的行业值运行:

$last_industry = null;

foreach ($case_studies as $c) {
   if ($last_industry != $c['user_industries_title']) {
      echo '</section><section>';
      $last_industry = $c['user_industries_title'];
      $changed = 1;
   } else {
      $changed = 0;
   }
}

此外,请注意制作 $ca 引用(&运算符)的一个陷阱 - 它在脚本的持续时间内仍然是一个引用,如果您依赖它在循环退出后保持其值,则可能会导致奇怪的副作用。

于 2012-05-29T15:56:10.173 回答
1

看看最后两行,你覆盖了你的$cwhich 是一个数组,$last_industry它是你在最后一次迭代中使用的字符串。重命名$c最后第二行中的 或将其完全删除。

顺便说一句:如果您将 PHP error_reporting 设置设置为 E_ALL,您会收到通知,这$c不再是一个数组!

于 2012-05-29T15:57:09.943 回答