我看过其他问题,但仍然无法解决这个问题。
我有以下json格式的iso国家/地区代码:
[
{
"code": "ZA"
},
{
"code": "VN"
},
{
"code": "IN"
},
{
"code": "AO"
},
{
"code": "IN"
},
{
"code": "IN"
}
]
我正在尝试使用array_count_values
对值进行计数,但是在更大的数据集上却失败了,我也不知道为什么。
我的代码:
这有效(小数据集):
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$json = file_get_contents('https://gist.githubusercontent.com/colinwilson/975c8a8509443b9c9b662816189c5012/raw/19743e79e51b59563750fe2db4283d1c95eb8023/data_sm.json');
$json = json_decode($json, true);
$json = array_count_values(array_column($json, "code"));
print_r($json);
result:
Array
(
[ZA] => 1
[VN] => 1
[IN] => 3
[AO] => 1
)
这不是(较大的数据集):
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$json = file_get_contents('https://gist.githubusercontent.com/colinwilson/33994f94111321963dd8abd5ed6607b0/raw/e36ba410bdf9d0fefe9c057a90e93b52cf00c267/data.json');
$json = json_decode($json, true);
$json = array_count_values(array_column($json, "code"));
print_r($json);
result:
PHP Warning: array_count_values(): Can only count STRING and INTEGER values! in C:\Users\colinwilson\Downloads\json_test.php on line 10
Warning: array_count_values(): Can only count STRING and INTEGER values! in C:\Users\colinwilson\Downloads\json_test.php on line 10
Array
(
[ZA] => 16
[VN] => 187
[IN] => 114
[AO] => 5
[TN] => 16
[HK] => 2
[LB] => 10
[BG] => 18
.......
正在发生什么,导致对较大数据集发出警告?我该如何解决?
答案 0 :(得分:2)
问题就在源数据中:
{
"code": null
},
在混合中添加array_filter()
将解决该问题:
$json = array_count_values(array_filter(array_column($json, "code")));
如果不将callable
传递给array_filter()
,它将仅过滤掉虚假的元素,例如null
。
答案 1 :(得分:0)
应阅读错误信息。您的数据中包含的内容不是字符串或整数。
$data = [
'ZA' => 16,
'VN' => 187,
'xx' => []
];
array_count_values($data);
输出与数组包含不是字符串或整数的元素相同的错误消息。