2016-12-26 47 views
1

我有這樣的一個數組包含在年底包含特定字符串計數陣列關鍵

陣列例如具有相同名稱的關鍵,但與數:

Array 
(
    [field_name0] => name 
    [field_name1] => sku_package_height 
    [field_name2] => sku_package_width 
    [custom_field] => 13 
    [attribute] => 'test' 
    [field_name3] => sku_package_length 
    [field_name4] => sku_package_weight 
) 

從上面的例子中,我想怎麼算許多記錄具有包含field_name數組鍵,所以結果我想會5

+0

的ISNUMERIC可以更新與實際PHP數組你的問題? –

回答

1

你可以像下面: -

<?php 
$original_array = Array 
(
    'field_name0' => 'name', 
    'field_name1' => 'sku_package_height', 
    'field_name2' => 'sku_package_width', 
    'custom_field' => 13, 
    'attribute' => 'test', 
    'field_name3' => 'sku_package_length', 
    'field_name4' => 'sku_package_weight' 
); 
$search = "field_name"; 
$counter = 0; 
foreach($original_array as $key=> $value){ 
    if(strstr($key,$search)){ 
     $counter = $counter+1; 
    } 
} 

echo $counter; 

輸出: - https://eval.in/704506

或者

<?php 
$original_array = Array 
(
    'field_name0' => 'name', 
    'field_name1' => 'sku_package_height', 
    'field_name2' => 'sku_package_width', 
    'custom_field' => 13, 
    'attribute' => 'test', 
    'field_name3' => 'sku_package_length', 
    'field_name4' => 'sku_package_weight', 
); 
$search = "field_name"; 
$counter = 0; 
foreach($original_array as $key=> $value){ 
    if(is_numeric(strpos($key,$search))){ 
     $counter = $counter+1; 
    } 
} 

echo $counter; 

輸出: - https://eval.in/704518

+0

我認爲strpos應該像這樣使用:'strpos($ keys_arr,$ search)'!我對嗎? –

0
<?php 
$array=array("field_name0"=>"name","field_name1"=>"sku_package_height ","field_name2"=>"sku_package_width","custom_field"=>"13","attribute"=>"test","field_name3"=>"sku_package_length", "field_name4"=>"sku_package_weight"); 

echo $arraykey= count(preg_grep("/^field_name(\d)+$/",array_keys($array))); 
?> 
+0

結果是0 –

+0

你必須在這裏重放$ array與你的變量 - > array_keys($ array) – 2016-12-26 10:17:56

+0

結帳更新的版本你應該知道我想說什麼 – 2016-12-26 10:22:10

2

,你可以這樣做:

$count = 0; 
foreach($array as $key => $value){ 

    if(strpos($key,"field_name") > -1){ 
     $count++; 
    } 

} 

$count將有k的數餘仁生。

+0

結果是0 –

+0

讓我測試它! –

+0

試試這個strpos($ key,「field_name」)> -1'。更新了答案 –

1

檢查字符串中的位置「FIELD_NAME」的關鍵

$i= 0; 
foreach($arrayfields as $keys => $values){ 

    if (is_numeric(strpos($keys,"field_name"))){ 
     $i++; 
    } 

} 
echo $i;