【问题标题】:How to count number of consecutive null values in array如何计算数组中连续空值的数量
【发布时间】:2020-01-28 14:01:21
【问题描述】:

我有一组客户,其中包含一组嵌套的付款。

"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"
]

我需要为每个客户计算连续付款的金额,从数组顶部的 0.00 开始。

所以我需要它返回如下内容:

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

我尝试了一堆 while 和 foreach 循环,但无法让它工作:

@php($count = 0)

    @foreach($array as $arr)

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

    @endforeach

【问题讨论】:

  • 不是很清楚,根据你的例子。"customer_1" 的值是211.79+206.20+220.90?
  • 我需要计数连续的“0.00”付款,而不是付款总和。客户 1 从数组顶部没有连续的“0.00”付款,因此 customer_1 = 0。
  • 但我认为customer_1 有两个连续的'0.00',我错了吗?
  • 正确,但不是从数组的开头。他们的第一笔付款是 211.79,因此计数应为 0。
  • 我已经发布了我的答案,请检查一下。

标签: php arrays laravel


【解决方案1】:

检查第一个元素,如果是0.00,则只计算连续的0.00,或者直接断循环:

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

对于刀片:

@php($count = 0)

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

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

@endforeach
@endif

【讨论】:

  • 欣赏刀片语法!干得好。
【解决方案2】:

你在 if 条件中为变量赋值,你需要在 if 条件中比较“0.00”。

@php($count = 0)

  @foreach($array as $arr)

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

 @endforeach

【讨论】:

【解决方案3】:
$sum = 0;

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

echo $sum;

试试这个@dexx

【讨论】:

  • 嘿,感谢您的回复,但是这是对值求和,我需要从数组开头计算连续的“0.00”付款。
猜你喜欢
  • 2011-07-12
  • 2021-02-14
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 2014-01-06
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多