PHP计数数组中的值

时间:2012-03-28 14:02:36

标签: php codeigniter

我有这样的代码:

<?php if(isset($global_info_results)): ?>
   <?php echo count($global_info_results) ?>
   <span>Mali Oglasi: </span>
   <?php foreach ($global_info_results as $result) : ?>
      <?php if($result->info_type_id == 1) : ?>
         <p><?php echo $result->name?></p>
      <?php endif ?>
   <?php endforeach; ?>
<?php endif ?>

如何计算数组中的特定值(例如,我想计算结果有多少info_type_id == 1)。

2 个答案:

答案 0 :(得分:3)

  <?php $a = 0
   foreach ($global_info_results as $result)
    if($result->info_type_id == 1)
      { $a = $a + 1}
     End Foreach?>

  <span>Mali Oglasi: </span>
  <?php foreach ($global_info_results as $result) : ?>
      <?php if($result->info_type_id == 1) : ?>
         <p><?php echo $result->name?></p>

答案 1 :(得分:2)

您可以使用array_filter生成一个与您想要计数的条件匹配的值数组,然后对结果运行计数。下面的示例返回数组中元素数大于4的元素数:

$items = array (1, 2, 3, 4, 5, 6, 7, 8, 9);
$itemsOfInterest = array_filter ($items, function ($elem) {return ((int) $elem > 4);})
echo (count ($itemsOfInterest));