执行PHP循环直到数组结束或达到一定的迭代次数?
我希望接收一个数组作为输入,从中筛选值,然后作为另一个数组输出。该函数最多应循环执行PHP循环直到数组结束或达到一定的迭代次数?,php,loops,for-loop,foreach,while-loop,Php,Loops,For Loop,Foreach,While Loop,我希望接收一个数组作为输入,从中筛选值,然后作为另一个数组输出。该函数最多应循环x次迭代 例如,如果我想输出输入的所有值,我会使用: <?php $i=0; foreach ($array as $data) { if ($data['type'] != 'some_value') { $formatted_array[$i] = $data; $i++; } } return $formatted_array; 您在正确的轨道上-
x次
迭代
例如,如果我想输出输入的所有值,我会使用:
<?php
$i=0;
foreach ($array as $data) {
if ($data['type'] != 'some_value') {
$formatted_array[$i] = $data;
$i++;
}
}
return $formatted_array;
您在正确的轨道上-您可以在达到计数时退出foreach
循环。使用foreach
对整个数组进行迭代,如果从未达到所述的最大计数,则将处理整个数组。但是如果你达到最大值,跳出循环
$i = 0;
// Don't allow more than 5 if the array is bigger than 5
$maxiterations = 5;
foreach ($array as $data) {
if ($i < $maxiterations) {
if ($data['type'] != 'some_value') {
$formatted_array[$i] = $data;
$i++;
}
}
else { // Jump out of the loop if we hit the maximum
break;
}
}
return $formatted_array;
<?php
$i=0;
foreach ($array as $data) {
if ($data['type'] != 'some_value') {
$formatted_array[$i] = $data;
$i++;
if($i>$maxAllowedElements) // here $i can serve as the counter and you can define //$maxAllowedElements to whatever value you like.
break;
}
}
return $formatted_array;
$i=0;
//如果阵列大于5,则不允许超过5
$maxiterations=5;
foreach($数组作为$数据){
如果($i<$maxiterations){
如果($data['type']!='some_value'){
$formatted_数组[$i]=$data;
$i++;
}
}
否则{//如果我们达到最大值,就跳出循环
打破
}
}
返回$U数组;
在循环时使用:
$i = 0;
$limit = 10;
$count = count($array);
while ($i < $limit && $i < $count) {
$data = $array[$i];
// your code here
++$i;
}
$i=0;
$limit=10;
$count=计数($array);
而($i<$limit&$i<$count){
$data=$array[$i];
//你的代码在这里
++$i;
}
$max\u迭代次数=100;
对于($i=1;$i您熟悉break
语句吗
用户foreach循环,并在每次输入代码内部条件时维护一个计数器变量。如果达到所需的数字元素,即计数器达到某个值,则中断循环
$i = 0;
// Don't allow more than 5 if the array is bigger than 5
$maxiterations = 5;
foreach ($array as $data) {
if ($i < $maxiterations) {
if ($data['type'] != 'some_value') {
$formatted_array[$i] = $data;
$i++;
}
}
else { // Jump out of the loop if we hit the maximum
break;
}
}
return $formatted_array;
<?php
$i=0;
foreach ($array as $data) {
if ($data['type'] != 'some_value') {
$formatted_array[$i] = $data;
$i++;
if($i>$maxAllowedElements) // here $i can serve as the counter and you can define //$maxAllowedElements to whatever value you like.
break;
}
}
return $formatted_array;
array_filter不是很好地解决了这个问题吗?我喜欢这个,它很适合我现有的代码。为什么你会选择这个而不是meager的while
循环解决方案呢?@Joe如果从头开始做,我可能会使用while循环,但这只是对你已经编写的代码的一个小小的修改。你走对了方向-你可以退出当达到计数时,使用foreach循环。使用foreach循环遍历整个数组,如果从未达到指定的最大计数,则将处理整个数组。但如果达到最大值,则跳出循环。也可以使用for循环:for($i=0;$i<$limit&&$i<$count;$i++)
<?php foreach($usersinglevideodata1 as $userkey=>$uservalue){
for($i = 0; $i < 5; $i++){if($uservalue['com_video'.$i.''] !=""){ if ($Count < 3){?>
<div class="col-sm-4">
<iframe width="100%" height="120" src="https://www.youtube.com/embed/<?php echo youtube_id($uservalue['com_video'.$i.'']);?>" frameborder="0" allowfullscreen></iframe>
</div>
<?php $Count++;}else{break;}}}?>
<?php }}?>