简体   繁体   English

如何将此循环限制为特定数字?

[英]how do I restrict this loop to a particular number?

below is from part of a loop 下面是循环的一部分

foreach($dataSet as $cType => $cPercentage){ echo $cType ."=". $cPercentage; }

this out put datas depend on array. 这个输出数据依赖于数组。 what I want is I want to run this loop to only a particular number of times. 我想要的是我想要将此循环运行到特定次数。 say 8 times. 说8次。

$nLoop = 0;
foreach($dataSet as $cType => $cPercentage){
  if ($nLoop++ == 8)
    break;
  echo $cType ."=". $cPercentage;
}

If you mean by "to a number", do you mean like "8 times"? 如果你的意思是“对一个数字”,你的意思是“8次”吗? That you could do by 你可以做到的

 $i=0;   
foreach($dataSet as $cType => $cPercentage){
    if($i==8){break;} 
    $i++;
    echo $cType ."=". $cPercentage; 
}

This should work for numeric & associative arrays 这适用于数字和关联数组

$count = 0;
foreach($dataSet as $cType => $cPercentage) {
    echo $cType ."=". $cPercentage;
    if (++$count > 8) break;
}

Possibly, but not real advantage 可能,但不是真正的优势

$cappedArray = array_slice($dataSet, 0, 8, true);
foreach($cappedArray as $cType => $cPercentage) {
    echo $cType ."=". $cPercentage;
}

您可以使用for循环为您执行此操作

Try a while loop 尝试一下while循环

$i = 0;
while($ds = each($dataSet) && $i < 8) {
   echo $ds['key']. '='.$ds['value'];
   $i++;
}

You can also use another type of loop, eg while : 您也可以使用其他类型的循环,例如, while

reset($dataSet);
$i = 8;
while((list($cType, $cPercentage) = each($dataSet)) && $i--) {
    echo $cType, ."=". $cPercentage;
}
reset($dataSet);

Reference: reset , each , list 参考: reseteachlist

Explanation: 说明:

each returns the key and value of the item the internal array pointer points to as array and advances the internal pointer. each返回内部数组指针指向的项的键和值作为数组并前进内部指针。 list assignes the array of key and value to two variables and returns the array. list将键和值数组分配给两个变量并返回数组。 $i-- decrements the counter variable. $i--递减计数器变量。
The loop will stop if either there are no elements in the array anymore (thus the array implicitly returned by list will be empty and evaluate to false ) or if $i is 0 . 如果数组中没有元素,则循环将停止(因此list隐式返回的数组将为空并且计算为false )或者$i0

If you want to truncate size of array you can use array_slice 如果要截断数组的大小,可以使用array_slice

so your code would look like this: 所以你的代码看起来像这样:

foreach(array_slice($dataSet, 0, 8) as $cType => $cPercentage){ echo $cType ."=". $cPercentage; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM