如何获取数组中特定值的数量?

时间:2015-02-24 03:26:17

标签: php arrays count

我有一个多维数组。我想得到所有数组中特定值的计数。主数组中的这个数组取决于我添加了多少条评论。

这是我的阵列:

array(3) {
  [0]=>
  array(11) { 
    ["comment_id"]=> string(1) "1" 
    ["user_Id"]=> string(1) "2" 
    ["comment"]=> string(18) "Commented! edited!" 
    ["comment_datetime"]=> string(19) "2015-02-20 04:24:28" 
    ["update_at"]=> string(19) "2015-02-20 04:23:18" 
    ["user"]=> string(18) "Nishan Weerasinghe" 
    ["delete"]=> string(1) "0" 
    ["username"]=> string(6) "Nishan" 
    ["picture_id"]=> NULL 
    ["picture"]=> NULL 
    ["picture_ext"]=> NULL 
  } 

  [1]=> 
  array(11) { 
    ["comment_id"]=> string(2) "48" 
    ["user_Id"]=> string(1) "2" 
    ["comment"]=> string(4) "here" 
    ["comment_datetime"]=> string(19) "2015-02-23 12:58:00" 
    ["update_at"]=> string(0) "" 
    ["user"]=> string(18) "Nishan Weerasinghe" 
    ["delete"]=> string(1) "0" 
    ["username"]=> string(6) "Nishan" 
    ["picture_id"]=> NULL 
    ["picture"]=> NULL 
    ["picture_ext"]=> NULL 
  } 
  [2]=> 
  array(11) { 
    ["comment_id"]=> string(2) "49" 
    ["user_Id"]=> string(1) "2" 
    ["comment"]=> string(3) "dfg" 
    ["comment_datetime"]=> string(19) "2015-02-23 14:46:56" 
    ["update_at"]=> string(0) "" 
    ["user"]=> string(18) "Nishan Weerasinghe" 
    ["delete"]=> string(1) "1" 
    ["username"]=> string(6) "Nishan" 
    ["picture_id"]=> NULL 
    ["picture"]=> NULL 
    ["picture_ext"]=> NULL 
  }
}

我想知道主数组中有多少["delete"]=> 0(答案应该是2,根据前ex。)。

4 个答案:

答案 0 :(得分:2)

$counter = 0;
foreach($results as $result){
    if($result['delete'] == "0"){
        $counter++;
    }
}
echo $counter;

就像评论所说的简单的foreach和一些数学。

答案 1 :(得分:0)

只需使用foreach

$count=0;  
foreach($yourarray as $a){

  if($a['delete']=='1')
      $count++;

}

答案 2 :(得分:0)

你可以使用这样的函数(需要PHP> 5.5.0):

echo array_count_values(array_column($array_string, 'delete'))[0];

答案 3 :(得分:0)

按如下方式应用foreach循环:

$count = 0;
foreach($yourarray as $counter){
    if($counter['delete'] == "0"){
        $count++;
    }
}
echo $count;