简体   繁体   中英

How to count number of consecutive null values in array

I have an array of customers that has a nested array of payments.

"customer_1" => array:4 [▼
 0 => "211.79"
 1 => "206.20"
 2 => "0.00"
 3 => "0.00"
 4 => "220.90"
]

 "customer_2" => array:4 [▼
 0 => "0.00"
 1 => "0.00"
 2 => "0.00"
 3 => "0.00"
 4 => "220.90"
]

I need to count, for each customer, the amount of consecutive payments, starting from the top of the array that are 0.00.

So I would need it to return something like:

"customer_1" => 0
"customer_2" => 4

I've tried a bunch of while and foreach loops but can't get it to work:

@php($count = 0)

    @foreach($array as $arr)

        @if($arr = "0.00")
            @php($count = $count + 1)
        @else
            @continue
        @endif

    @endforeach

Check the first element, if it is 0.00 , then just calculate the consecutive 0.00 , or just break the loop:

$count = 0;
if ($array[0] == "0.00") {
    foreach($array as $item) {
        if($item == "0.00") {
            $count += 1;
        } else {
            break;
        }
    }
}
return $count;

For blade:

@php($count = 0)

@if($arr[0] == "0.00")
@foreach($array as $arr)

   @if($arr == "0.00")
      @php($count += 1)
   @else
      @break
   @endif

@endforeach
@endif

you are assigning value to variable inside if condition , you need to compare "0.00" inside if condition .

@php($count = 0)

  @foreach($array as $arr)

    @if($arr == "0.00")
        @php($count = $count + 1)
    @else
        @continue
    @endif

 @endforeach
$sum = 0;

foreach($items as $item) {
    $sum += $item;
}

echo $sum;

Try this @dexx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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