我有一个像这样的数组包含同名但前面有数字的键
数组示例:
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 :(得分:2)
你可以这样做:
$count = 0;
foreach($array as $key => $value){
if(strpos($key,"field_name") > -1){
$count++;
}
}
$count
会有多个键。
答案 1 :(得分: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
答案 2 :(得分:1)
检查字符串位置&#34; field_name&#34;的isnumeric。在密钥
$i= 0;
foreach($arrayfields as $keys => $values){
if (is_numeric(strpos($keys,"field_name"))){
$i++;
}
}
echo $i;
答案 3 :(得分: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)));
?>