【问题标题】:Count associative array with condition in php [duplicate]在php中计算带有条件的关联数组[重复]
【发布时间】:2021-09-09 21:22:08
【问题描述】:

我正在使用 php,我有关联数组,我想计算总数 键为“IsRatingQuestion”且值为 =“1”的数组(使用循环)数 这是我的数组

Array
(
    [0] => Array
        (
            [ques_id] => 2
            [question] => Please enter your mobile number.
            [IsRatingQuestion] => 0
            [ISSubQuestion] => 
            )

    [1] => Array
        (
            [ques_id] => 2
            [question] => Lorem Ipsum dummy text
            [IsRatingQuestion] => 
            [ISSubQuestion] => 
            )

    [2] => Array
        (
            [ques_id] => 15
            [question] => Would your recommend TOSSIN ?
            [IsRatingQuestion] => 1
            [ISSubQuestion] => 
            )

    [3] => Array
        (
            [ques_id] => 18
            [question] => which type of mobile you have ?
            [IsRatingQuestion] =>1 
            [ISSubQuestion] => 1
            )

这是我的 php 代码(现在计算所有记录/数组),我想计算键为“IsRatingQuestion”且值为 =“1”的数组,我该怎么做?提前致谢。

<?php   
    $count=count($rec);
    for ($j = "2"; $j < $count+"1"; $j++)
                        {
?>
    <li>Step <?php echo $j; ?></li>
<?php } ?>

【问题讨论】:

    标签: php arrays loops


    【解决方案1】:

    你可以使用array_filter函数来过滤IsRatingQuestion=1的项目

    $filterdArray = array_filter($rec,function($item){
        if($item['IsRatingQuestion']==1){
            return $item;
        }
    });
    count($filterdArray)
    

    【讨论】:

      【解决方案2】:

      您可以保留一个计数器,遍历数组,当条件为真时,添加到计数器中。

      $count = 0;
      foreach($entries as $entry) {
          if (isset($entry['isRatingQuestion']) && $entry['isRatingQuestion'] === 1) {
              $count ++;
          }
      }
      echo "$count entries match the condition";
      

      【讨论】:

        【解决方案3】:

        遍历数组,检查它是否等于 1,如果它确实添加到您的计数器;示例:

        $count = 0;
        foreach($yourArray as $val){
            if(isset($val['isRatingQuestion']) && $val['IsRatingQuestion'] === 1){
                $count++;
            }
        }
        echo $count;
        # Output: 2
        

        【讨论】:

          猜你喜欢
          • 2015-12-30
          • 2011-11-26
          • 2021-03-23
          • 1970-01-01
          • 2017-10-26
          • 1970-01-01
          • 1970-01-01
          • 2023-03-15
          • 1970-01-01
          相关资源
          最近更新 更多