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

最後の2行を見てください。これは、最後の反復で使用した文字列で$cある配列であるyourをオーバーライドします。$last_industry最後から2行目の名前を変更する$cか、完全に削除します。

ところで:PHPのerror_reporting設定をE_ALLに設定すると、通知されますが、それ$cはもはや配列ではありません!

于 2012-05-29T15:57:09.943 に答える