计算并打印 HTTP API 的值

Count and print values of HTTP API

寻求帮助计算 HTTP API 中存在的所有值。下面的link按日期输出多个数据点的值。我想要实现的是每个值的 count ,而不是

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。

例如 API 的 Link 是 https://demo.piwik.org/?module=API&method=Actions.get&idSite=7&period=day&date=last2&format=php&token_auth=anonymous

显示这个的 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");       
}

请注意,上面的 link 包含多个其他值,我想对它们做同样的事情,但为了确保这个问题的可读性,我将这些值保持简单并且只保留一个。

只需使用 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]);

工作演示:https://eval.in/930183

// 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>