计算特定的数组值开始

时间:2016-11-21 12:22:57

标签: php arrays

我有这个数组:

$array = array("pg_1","pg_2","pg_3","pg_4","pg_5","qr_1","qr_2","qr_3");

我想计算以pg开头的值。

到目前为止,我已尝试过以下代码:

$arraycount = array_count_values($array);

$countpg = $arraycount['pg%'];

我忘了我有钥匙和价值观:

$array = Array ( [pg_1] => 2 [pg_2] => 3 [pg_3] => 2 [pg_4] => 4 [pg_5] => 1 [gp_1] => 1 [gp_2] => 4 [gp_3] => 3 )

5 个答案:

答案 0 :(得分:3)

$array = array("pg_1","pg_2","pg_3","pg_4","pg_5","qr_1","qr_2","qr_3");

$count = count(array_filter($array, function($item) {
    return strpos($item, 'pg') === 0;
}));

echo $count;

您正在过滤以' pg'开头的项目。然后计算结果。

答案 1 :(得分:2)

  

使用以下方法: -

$ array = array(" pg_1"," pg_2"," pg_3"," pg_4"," pg_5&# 34;," qr_1"" qr_2"" qr_3&#34);

$search_val = preg_quote('pg', '*');

$result = preg_grep('*' . $search_val . '*', $array);

count($result);

答案 2 :(得分:2)

如果值包含pg,则递增$i

$array = array("pg_1","pg_2","pg_3","pg_4","pg_5","qr_1","qr_2","qr_3");
$i = 0;

foreach ($array as $value) {
    if (strpos($value, 'pg') !== false) { 
       $i++;
    }
}
echo $i;

刚刚注意到你的编辑......

对于关联数组,只需更改Foreach循环即可查看$key$value并查询$key而不是$value,如上所示示例

$array = ["pg_1" => 2, "pg_2" => 3, "pg_3" => 2, "pg_4" => 4, "pg_5" => 1, "gp_1" => 1, "gp_2" => 4, "gp_3" => 3];
$i = 0;

foreach ($array as $key => $value) {
    if (strpos($key, 'pg') !== false) { 
       $i++;
    }
}
echo $i;

答案 3 :(得分:2)

一线解决方案是使用 preg_grep 功能

尝试以下代码:

$array = array("pg_1","pg_2","pg_3","pg_4","pg_5","qr_1","qr_2","qr_3");
$count = count(preg_grep('/pg/',$array));
echo $count;

有关函数的更多参考,请参阅此链接 - http://php.net/manual/en/function.preg-grep.php

答案 4 :(得分:0)

我会在这里使用数组过滤器:

$array = array("pg_1","pg_2","pg_3","pg_4","pg_5","qr_1","qr_2","qr_3");

$c = count(array_filter($array, "getPG"));

function getPG($key)
{
    return strpos($key, "pg_") === 0;
}

echo 'count: ' .$c;

您将拥有以$c中存储的“pg_”开头的数组元素的正确计数。