从PHP数组中获取特定值的计数
我有一个数组,我想得到特定值的计数 结构如下:从PHP数组中获取特定值的计数,php,arrays,Php,Arrays,我有一个数组,我想得到特定值的计数 结构如下: Array ( [0] => Array ( [coupon_id] => 350 [coupon_title] => This is the title of coupons [coupon_code] => ABCD [coupon_type] => coupon ) [1] => Array ( [cou
Array (
[0] => Array (
[coupon_id] => 350
[coupon_title] => This is the title of coupons
[coupon_code] => ABCD
[coupon_type] => coupon
)
[1] => Array (
[coupon_id] => 350
[coupon_title] => This is the title of coupons
[coupon_code] => ABCD
[coupon_type] => no_coupon
)
)
现在我想得到优惠券
和无优惠券
我尝试通过
array\u value\u count
进行计算,但我得到的结果是,这只能计算字符串和值。您可以使用foreach循环来实现此目的
<?php
# Get the data from where you want to get the count
$array = array(
array('coupon_type' => 'coupon'),
array('coupon_type' => 'no_coupon')
);
# Count the variables
$count = array_count_values(array_column($array, 'coupon_type')));
print_r($count);
// Will show
// Array ( [coupon] => 1 [no_coupon] => 1 )
?>
$count_coupon=0;
$count_no_coupon=0;
foreach ( $array as $arr )
{
if( $arr['coupon_type'] == 'coupon' )
{
$count_coupon++;
}
else if( $arr['coupon_type'] == 'no_coupon' )
{
$count_no_coupon++;
}
为此,可以使用foreach循环
$count_coupon=0;
$count_no_coupon=0;
foreach ( $array as $arr )
{
if( $arr['coupon_type'] == 'coupon' )
{
$count_coupon++;
}
else if( $arr['coupon_type'] == 'no_coupon' )
{
$count_no_coupon++;
}
array\u value\u count(array\u列(“优惠券类型”)代码>数组值计数(数组列(“优惠券类型”)
@mohit-您想要总数还是出现次数。我相信array\u count\u values
返回该键在数组中出现的次数,而不是其值的总和。不要紧的是值在数组中的次数。。。所以这应该行得通。@mohit-您想要总数还是出现次数。我相信array\u count\u values
返回该键在数组中出现的次数,而不是其值的总和。不要紧的是值在数组中的次数。。。所以这应该行得通。