简体   繁体   English

foreach循环php中同名的总和值

[英]Sum values of same name in foreach loop php

How to SUM same value in forech if i have output like this 如果我有这样的输出,如何在Forech中求和

Array
(
    [0] => 200,2,
    [1] => 200,3,
    [2] => 300,5,
)

Output should be like 输出应该像

'200' => 5,
'300' => 5,

So group name 200 and SUM value so result is 2+3 所以组名200和SUM值,所以结果是2 + 3

$ga->requestReportData(
        ga_profile_id,
        array('date','pagePath'),
        array('pageviews'),
        '-pageviews',
        'ga:pagePathLevel1==/post/ && ga:pagePathLevel2=~^\/[0-9]+\/$',
        $date,
        $date,
    1);
    foreach ($ga->getResults() as $result) {
        $pageviews = $result->getPageviews();
        $pagepath = $result->getPagePath();
        if(is_numeric(get_part_url($pagepath))){
            print 'INSERT INTO stats (views,content_id) VALUES ("'.$pageviews.'","'.get_part_url($pagepath).'")';
        }
    }

get_part_url is just function to extract part of url. get_part_url只是提取一部分url的功能。

You can create a new array to group all your results into. 您可以创建一个新数组将所有结果分组。 Note you may receive notices about offsets, just check firstly the key isset() to stop this or use error_reporting(E_ERROR); 注意,您可能会收到有关偏移的通知,只需首先检查键isset()即可停止偏移或使用error_reporting(E_ERROR); to not show warnings. 不显示警告。

$groupedResults = array();

foreach ($ga->getResults() as $result) {
    $pageviews = $result->getPageviews();
    $pagepath = get_part_url($result->getPagePath());
    if(is_numeric($pagepath)) $groupedResults[$pagepath] += $pageviews;
}

You can then loop through these and run your DB queries. 然后,您可以遍历这些内容并运行数据库查询。

foreach ($groupedResults as $k => $v) {
     print 'INSERT INTO stats (views,content_id) VALUES ("'.$v.'","'.$k.'")';
}

See a working example here with example data. 请参阅此处工作示例以及示例数据。

Create a new array and sum the value. 创建一个新的数组并求和。

$newArray=array();
Foreach( $myarray as             $key=>$value)
{
   If(!isset($newArray[$key])
  {
     $newArray[$key]=$value;
  }
  Else
  {
     $newArray+=$value;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM