简体   繁体   中英

sum up values in an array php

I have got an array of site page view from various browsers and I am trying to search unique occurrence of specific browser from the the array and also sum up the total values for each.

Data in it crude form

$data = array(
            array("Browser Version", "Pageviews", "Visits"),
            array("Firefox 39.0", "93", "47"),
            array("Chrome 44.0.2403.125", "88", "26"),
            array("Chrome 44.0.2403.130", "34", "11"),
            array("Chrome 44.0.2403.107", "57", "10"),
            array("Chrome 44.0.2403.155", "22", "9"),
            array("Chrome 43.0.2357.134", "11", "4"),
            array("Chrome 44.0.2403.133", "5", "4"),
            array("Chrome 44.0.2403.89", "4", "3"),
            array("Opera 30.0.1835.125", "4", "3"),
            array("Opera 31.0.1889.99", "9", "3"),
            array("Chrome 43.0.2357.93", "2", "2"),
            array("Firefox 28.0", "5", "2"),
            array("BlackBerry 7.1.0.714", "1", "1"),
            array("Chrome 36.0.1985.135", "2", "1"),
            array("Firefox 40.0", "1", "1"),
            array("Internet Explorer 9.0", "2", "1")
);

Now I'm trying to search for specific browser and then sum up values for each

        $browsersArray = array();

            $browsersArray["Firefox"] = array(); 

            $browsersArray["Chrome"] = array();

            $browsersArray["Internet Explorer"] = array();

            $browsersArray["Safari"] = array();

            $browsersArray["Opera"] = array();  

$result_browser = '';
$result_browser_pageview = '';

$i = 0; 
foreach ($data as $data_row) { 
            $i++; 
            echo '<tr>';
    while (list($key, $value) = each ($data_row)) { 

        if($key == 0){
            $result_browser = $value;
        }
        elseif($key == 1){
            $result_browser_pageview = $value;
        }

            if($key == 0){      

                $firefoxSearchPos = stripos($result_browser, "Firefox");
                $chromeSearchPos = stripos($result_browser, "Chrome");
                $ieSearchPos = stripos($result_browser, "Internet Explorer");
                $safariSearchPos = stripos($result_browser, "Safari");
                $operaSearchPos = stripos($result_browser, "Opera");

                if($firefoxSearchPos !== false) {
                    $browsersArray["Firefox"][] = $result_browser_pageview;
                }
                elseif($chromeSearchPos !== false) {
                    $browsersArray["Chrome"][] = $result_browser_pageview;
                }
                elseif($ieSearchPos !== false) {
                    $browsersArray["Internet Explorer"][] = $result_browser_pageview;
                }
                elseif($safariSearchPos !== false) {
                    $browsersArray["Safari"][] = $result_browser_pageview;
                }
                elseif($operaSearchPos !== false) {
                    $browsersArray["Opera"][] = $result_browser_pageview;
                }
            }
    } // end while
} 

I have not been able to get the actual sum for each based on the $data array

Eg Firefox should give me a total pageview of 99 and a total visit of 50.

You have no math in your code, you are just putting the page views into a new element in the array with:

$browsersArray["Firefox"][] = $result_browser_pageview;

Should be something like:

$pageViews["Firefox"] += $result_browser_pageview;

+= takes the original value and adds to it. View more at Assignment Operators .

Why do you even have that while() loop? All you do is then check which key you're testing and skip most of the loop's iterations anyways. It's utterly pointless. This really stinks of cargo-cult programming.

How about simply:

foreach($data as $browser) {
    if (stripos($browser[0]), "Firefox") !== false ) {
       $browsersArray['Firefox'][] = $browser;
    }
    etc...
}

And an even more compact version would use a regex:

foreach($data as $browser) {
    if (preg_match('/^(Firefox|Chrome|Internet Explorer|etc...)/', $browser[0], $matches)) {
       $browsersArray[$matches[1]][] = $browser;
    } else {
       $browsersArray['unknown'][] = $browser;
    }
}

You could do something like

foreach (array('Firefox', 'Chrome', 'Opera', 'BlackBerry', 'Internet Explorer') as $browser) {
    $rows = array_filter($data, function($item) use ($browser) {
        return strpos($item[0], $browser) === 0;
    });
    $pageViews = array_sum(array_map(function($item) {
        return $item[1];
    }, $rows));

    // obviously you can create an array here too
    echo "$browser page views: $pageViews".PHP_EOL;
}

Which gives

Firefox page views: 99
Chrome page views: 225
Opera page views: 13
BlackBerry page views: 1
Internet Explorer page views: 2 

Try something like this:

$result = array();
foreach($data as $row){
    if(@$i++ < 1) continue; // skip first line
    $fullName = array_shift($row);
    preg_match('~^([^\d]+)\s\d~',$fullName,$nameGroup);
    $name = $nameGroup[1];
    array_map('intval',$row);
    if(isset($result[$name])){
        foreach($row as $key => $value){
            $result[$name][$key] += $value;
        }
    }else{
        $result[$name] = $row;
    }
}

var_dump($result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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