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