我有一个如下所示的示例对象数组,它是一个 json 解码数组。该对象数组中的索引 value1,value2,value3 将来可以增长到 value'n' 。我需要获取此对象数组中索引出现次数的计数。我怎样才能实现这一点?我正在使用 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 )
2 回答
慕的地10843
TA贡献1785条经验 获得超8个赞
您可以使用以下函数对数组元素进行拟合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));
- 2 回答
- 0 关注
- 106 浏览
添加回答
举报
0/150
提交
取消