如何获取数组中特定值的数量?
问题描述:
我有一个多维数组。我想在所有数组中获得特定值的计数。主数组中的这个数组取决于我添加了多少条评论。如何获取数组中特定值的数量?
这里是我的数组:
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)计数是有主阵列中。
答
$counter = 0;
foreach($results as $result){
if($result['delete'] == "0"){
$counter++;
}
}
echo $counter;
像评论说,一个简单的foreach和一些数学。
答
只是使用的foreach
$count=0;
foreach($yourarray as $a){
if($a['delete']=='1')
$count++;
}
答
你可以用这样的功能做到这一点(需要PHP> 5.5.0):
echo array_count_values(array_column($array_string, 'delete'))[0];
答
只是适用foreach循环如下:
$count = 0;
foreach($yourarray as $counter){
if($counter['delete'] == "0"){
$count++;
}
}
echo $count;
哪里是你的企图? 'count + array_filter'或者好的foreach应该就足够了 – Ghost 2015-02-24 03:31:15