简体   繁体   English

如何在 PHP 的数组中获取特定键的出现次数?

[英]How to get number of occurrences of a particular Key inside an array in PHP?

I have a got a sample object array like below,its a json decoded array.我有一个示例 object 数组,如下所示,它是一个 json 解码数组。 The indexes value1,value2,value3 inside this object array can grow upto value'n' in future.这个 object 数组中的索引 value1,value2,value3 将来可以增长到 value'n'。 I need to get count of those index occurences inside this object array.How can I achieved this?.我需要计算这个 object 数组中那些索引出现的次数。我怎样才能做到这一点? I am using PHP 5.6我正在使用 PHP 5.6

     stdClass Object(
             
         [general_rates] => Array
                 (
                    [0] => stdClass Object
                          (
                               [id] => 1
                               [item] => Item name
                               [cost1] => 
                               [cost2] => 
                               [cost3] => 60
  
                          )

                    [1] => stdClass Object
                           (
                               [id] => 2
                               [item] => 
                               [cost1] => N/A
                               [cost2] => N/A
                               [cost3] => 60
       
                            )
                         )

                        [value1] => EUROPE
                        [value2] => AMERICA
                        [value3] => FRANCE

                 )

You can fitler the array elements using the array_filter function:您可以使用array_filter调整数组元素:

$jsonStr = '{
    "general_rates" : [
        { "id" : 1, "item" : "Item name", "cost1": "", "cost2": "", "cost3": "" },
        { "id" : 2, "item" : "", "cost1": "N/A", "cost2": "N/A", "cost3": 60 }
    ],
    "value1" : "EUROPE",
    "value2" : "AMERICA",
    "value3" : "FRANCE"
}';

$decoded = json_decode($jsonStr, true);

// Filter the array elements which key start with 'value'
$filtered = array_filter($decoded, function ($key) {
    return strpos($key, 'value') === 0;
}, ARRAY_FILTER_USE_KEY);

var_dump(count($filtered));

Use preg_grep and a small regexp "starting with value":使用preg_grep和一个小的正则表达式“从值开始”:

$ar = ['value1', 'value2', 'no_vlue_here', 'and_here'];
$filtered = preg_grep('/^value/', $ar);
echo count($filtered);

Fiddle .小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM