我有一堆JSON对象存储在我的数据库中,具有用户输入,即
{ "items": [
{question_id: 5, answer_id: 4, is_correct: 1},
{question_id, 45, answer_id: 233, is_correct: 0},
...]
}我想要构建关于哪个answer_id的统计数据,其中回答最多的是question_id,等等。
我尝试过PHP关联数组,如下所示:
<?php
$stats = array();
foreach($jsonObject->items as $item)
{
$stats[$item->question_id][$item->answer_id]++;
}
?>我正在使用PHP,就像我使用AWK一样,它可以工作,但问题是,我收到了很多类似于此的警告
Undefined offset: 23026其中23026是问题或答案的id。
如何调试/确保统计数据的准确性?有更好的方法吗?
发布于 2015-08-28 16:41:43
出现这些通知,是因为您试图在第一次出现问题或回答id时增加一个不存在的值。如果您想在没有警告的情况下运行您的脚本,您只需检查它是否已经设置。一些应该工作的示例代码:
<?php
$stats = array();
foreach ($jsonObject->items as $item) {
if (isset($stats[$item->question_id][$item->answer_id])) {
$stats[$item->question_id][$item->answer_id]++;
} else {
// Set to 1 if not exist
$stats[$item->question_id][$item->answer_id] = 1;
}
}
?>https://stackoverflow.com/questions/32275687
复制相似问题