寻找帮助计算HTTP API中存在的所有值。下面的链接按日期输出多个数据点的值。我想要实现的是每个值上的计数,而不是
a:2:{s:10:"2018-01-03";a:9:{s:12:"nb_pageviews";d:2031;}s:10:"2018-01-04";a:9:{s:12:"nb_pageviews";d:25;}
我想输出上面的nb_pageviews作为一个关键日期的值 - 2056年。
显示这个的PHP是
$url = "https://demo.piwik.org/";
$url .= "?module=API&method=Actions.get";
$url .= "&idSite=7&period=day&date=last2";
$url .= "&format=php";
$url .= "&token_auth=anonymous";
$fetched = file_get_contents($url);
$content = unserialize($fetched);
// case error
if (!$content) {
print("NO DATA");
}
foreach ($content as $row) {
$pageviews = $row['nb_pageviews'];
print("<div>$pageviews</div>\n");
}
请注意,上面的链接包含我想要做的同样多个其他值,但为了确保这个问题的可读性,我将值保持简单并且只保留了一个。
答案 0 :(得分:1)
只需使用combined assignment operator,并确保在循环之前设置默认值为0.
$fetched = 'a:2:{s:10:"2018-01-03";a:9:{s:12:"nb_pageviews";d:2031;s:17:"nb_uniq_pageviews";d:964;s:12:"nb_downloads";d:2;s:17:"nb_uniq_downloads";d:2;s:11:"nb_outlinks";d:68;s:16:"nb_uniq_outlinks";d:64;s:11:"nb_searches";d:33;s:11:"nb_keywords";d:16;s:19:"avg_time_generation";d:0.78600000000000003;}s:10:"2018-01-04";a:9:{s:12:"nb_pageviews";d:25;s:17:"nb_uniq_pageviews";d:10;s:12:"nb_downloads";i:0;s:17:"nb_uniq_downloads";i:0;s:11:"nb_outlinks";d:1;s:16:"nb_uniq_outlinks";d:1;s:11:"nb_searches";d:2;s:11:"nb_keywords";d:2;s:19:"avg_time_generation";d:0.79300000000000004;}}';
$content = unserialize($fetched);
// case error
if (!$content) {
print("NO DATA");
}
$pageviews = 0;
$uniq_pageviews = 0;
// and on, with your other vars you're looking to sum...
foreach ($content as $row) {
$pageviews += $row['nb_pageviews'];
$uniq_pageviews += $row['nb_uniq_pageviews'];
}
var_export(['pageviews' => $pageviews, 'uniq_pageviews' => $uniq_pageviews]);
// Output
array (
'pageviews' => 2056.0,
'uniq_pageviews' => 974.0,
)
要打印这些值,您可以使用以下内容替换var_export
行:
$data = [
'pageviews' => $pageviews,
'uniq_pageviews' => $uniq_pageviews
];
您可以在某些HTML中输出:
<div class="col-md-4"><?php echo $data['pageviews']; ?></div>
<div class="col-md-4"><?php echo $data['uniq_pageviews']; ?></div>