在某些条件下打破foreach

时间:2018-01-15 09:42:33

标签: php arrays foreach break

我的学校任务有些问题。由于经验不足,我对操作数组感到困惑。我使用foreach从数组中获取值,然后我希望在某些条件下得出结果:

  1. 已设置变量$total_words
  2. 中的字数
  3. foreach中有条件。 如果 $total words未传递数组值中的字数,则打印所有数组值。但要其他打破所有字词然后按最后一个字数停止。
  4. 有关详细信息,您可以看到我想要的结果

    $array = array(
      "There are many ways to get to Windows 10 Advanced Startup Options.",
      "On many laptops, hitting F11 as soon as you power on will get you there.",
      "Booting off an install disk and hitting Next then Repair will do the job",
      "n ....................."
    );
    
    $total_words = 4;
    
    foreach($array as $value){
      $count = explode(" ", $value);
      if( count($count) <= $total_words){
        echo $value. "\n\n";
      } else {
        //echo i do something
        break;
      }
    }
    
    //output $total_words = 4;
    /* There are many */
    
    //output $total_words = 12;
    /* There are many ways to get to Windows 10 Advanced Startup Options. */
    
    //output $total_words = 16;
    /* There are many ways to get to Windows 10 Advanced Startup Options. */
    /* On many laptops, hitting */
    
    //output $total_words = 20000;
    /* There are many ways to get to Windows 10 Advanced Startup Options. */
    /* On many laptops, hitting F11 as soon as you power on will get you there. */
    /* Booting off an install disk and hitting Next then Repair will do the job */
    /* n ..................... */
    

1 个答案:

答案 0 :(得分:0)

这是我将使用的方法 - 假设我理解了这个问题。检查每次迭代时的单词计数,并根据需要截断文本或减少单词容差。

代码:(演示:https://3v4l.org/JFYsd

function word_limiter($sentences,$word_allowance){
    $text='';
    foreach($sentences as $sentence){
        $words=explode(' ',$sentence);
        $word_count=count($words);
        if($word_count>$word_allowance){
            $text.=implode(' ',array_slice($words,0,$word_allowance));
            // do something
            break;
        }elseif($word_count==$word_allowance){
            $text.=$sentence;
            break;
        }else{
            $text.="$sentence\n";
            $word_allowance-=$word_count;  // reduce allowance for next iteration
        }
    }
    return $text;
}

$array = array(
  "There are many ways to get to Windows 10 Advanced Startup Options.",
  "On many laptops, hitting F11 as soon as you power on will get you there.",
  "Booting off an install disk and hitting Next then Repair will do the job",
  "n ....................."
);

echo word_limiter($array,4),"\n\n";
echo word_limiter($array,12),"\n\n";
echo word_limiter($array,16),"\n\n";
echo word_limiter($array,27),"\n\n";

输出:

There are many ways

There are many ways to get to Windows 10 Advanced Startup Options.

There are many ways to get to Windows 10 Advanced Startup Options.
On many laptops, hitting

There are many ways to get to Windows 10 Advanced Startup Options.
On many laptops, hitting F11 as soon as you power on will get you there.