Nice programing

foreach 루프에서 반복 횟수 계산

nicepro 2020. 12. 27. 20:49
반응형

foreach 루프에서 반복 횟수 계산


foreach의 항목 수를 계산하는 방법은 무엇입니까?

총 행을 계산하고 싶습니다.

foreach ($Contents as $item) {
    $item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}

감사.


우선 배열의 요소 수만 알고 싶다면 count. 이제 질문에 답하려면 ...

foreach의 항목 수를 계산하는 방법은 무엇입니까?

$i = 0;
foreach ($Contents as $item) {
    $i++;
    $item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}

여기에서 답변을 볼 수도 있습니다.


에서 할 필요가 없습니다 foreach.

사용하십시오 count($Contents).


foreach ($Contents as $index=>$item) {
  $item[$index];// if there are 15 $item[number] in this foreach, I want get the value : 15
}

count($Contents);

또는

sizeof($Contents);

이 문제를 해결할 수있는 몇 가지 방법이 있습니다.

foreach () 전에 카운터를 설정 한 다음 가장 쉬운 방법을 반복 할 수 있습니다.

$counter = 0;
foreach ($Contents as $item) {
      $counter++;
       $item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}

$Contents = array(
    array('number'=>1), 
    array('number'=>2), 
    array('number'=>4), 
    array('number'=>4), 
    array('number'=>4), 
    array('number'=>5)
);

$counts = array();

foreach ($Contents as $item) {
    if (!isset($counts[$item['number']])) {
        $counts[$item['number']] = 0;
    }
    $counts[$item['number']]++;
}

echo $counts[4]; // output 3

foreach ($array as $value)
{       
    if(!isset($counter))
    {
        $counter = 0;
    }
    $counter++;
}

// 코드가 올바르게 표시되지 않으면 죄송합니다. :피

// 카운터 변수가 위가 아니라 foreach에 있기 때문에이 버전이 더 마음에 듭니다.


시험:

$counter = 0;
foreach ($Contents as $item) {
          something 
          your code  ...
      $counter++;      
}
$total_count=$counter-1;

당신이 할 수있는 sizeof($Contents)또는count($Contents)

이것도

$count = 0;
foreach($Contents as $items) {
  $count++;
  $items[number];
}

초기 값이 0.

For every loop, increment the counter value by 1 using $counter = 0;

The final counter value returned by the loop will be the number of iterations of your for loop. Find the code below:

$counter = 0;
foreach ($Contents as $item) {
    $counter++;
    $item[number];// if there are 15 $item[number] in this foreach, I want get the value `: 15`
}

Try that.

ReferenceURL : https://stackoverflow.com/questions/6220546/count-number-of-iterations-in-a-foreach-loop

반응형