2016-11-21 45 views
0

我有此數組:計數特定陣列值開始的東西

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

我想指望這是價值觀開始與皮克。

到目前爲止,我已經嘗試下面的代碼:

$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) 

回答

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
$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' 啓動項目然後計算結果。

2

使用以下方法: -

$陣列=陣列( 「pg_1」, 「pg_2」, 「pg_3」, 「pg_4」, 「pg_5」, 「qr_1」, 「qr_2」 「qr_3」);

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

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

count($result); 
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

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_」開頭的數組元素的正確計數。