Viewed   172 times

i have an array:

Array 
(
[0] => Array
    (
        [setid] => 2
        [income] => 100
    )

[1] => Array
    (
        [setid] => 2
        [income] => 120
    )

[2] => Array
    (
        [setid] => 3
        [income] => 700
    )
)

i need to find entrys with the same setid, sum their income up and delete duplicate entrys - in the end it should look like this:

Array
(
[0] => Array
    (
        [setid] => 2
        [income] => 220
    )

[1] => Array
    (
        [setid] => 3
        [income] => 700
    )
)

does someone know a sophosticated solution for my problem or do i have to take the long road and do every step manually?

thanks and greetings

 Answers

3

Just create a new array which you make fast adressable by using the setid as key. And reindex the array at the end.

$result = array();
foreach ($array as $val) {
    if (!isset($result[$val['setid']]))
        $result[$val['setid']] = $val;
    else
        $result[$val['setid']]['income'] += $val['income'];
}
$result = array_values($result); // reindex array
Tuesday, November 22, 2022
4

You need to iterate over your results, adding a new entry to the output when you encounter a new team, or updating the points value when you find the same team again. This is most easily done by initially indexing the output by the team name, and then using array_values to re-index the array numerically:

$teams = array();
foreach ($results as $result) {
    $team = $result['team'];
    if (!isset($teams[$team])) {
        $teams[$team] = array('team' => $team, 'points' => $result['punti']);
    }
    else {
        $teams[$team]['points'] += $result['punti'];
    }
}
$teams = array_values($teams);
print_r($teams);

Output (for your sample data):

Array
(
    [0] => Array
        (
            [team] => Red Bull Racing
            [points] => 418
        )
    [1] => Array
        (
            [team] => Scuderia Ferrari
            [points] => 353
        )
    [2] => Array
        (
            [team] => Mercedes-AMG
            [points] => 516
        )
    [3] => Array
        (
            [team] => Racing Point F1
            [points] => 147
        )
    [4] => Array
        (
            [team] => Haas F1
            [points] => 127
        )
)

Demo on 3v4l.org

Friday, August 12, 2022
 
2

And here is the solution :)

$sumData = array_map('prepare_data', $projects_grouped_by_year);
function prepare_data($v) {
    $arr = ['year' => current(array_column($v, 'year_actual'))];
    $arr['project_capacity_sum'] = array_sum(array_column($v, "project_capacity"));
    $arr['C2_capacity_sum'] = $arr['C1_capacity_sum'] = 0;
    $arr['H2_capacity_sum'] = $arr['H1_capacity_sum'] = 0;

    foreach ($v as $item) {
        // summing up companies shares
        $c_types = array_column($item['companies'], 'company_type');
        $c_shares = array_column($item['companies'], 'capacity_share');
        foreach ($c_types as $k => $v) {
            $arr[$v ."_capacity_sum"] += $c_shares[$k];
        }
        // summing up holders shares
        $h_types = array_column($item['holders'], 'holder_type');
        $h_shares = array_column($item['holders'], 'holder_share');
        foreach ($h_types as $k => $v) {
            $arr[$v ."_capacity_sum"] += $h_shares[$k];
        }        
    }

    return $arr;
}

print_r($sumData);
Wednesday, September 14, 2022
1

Solution using data.table:

require(data.table)
df <- structure(list(year = c(2015, 2015), ID = c(200, 200), Lats = c(30.5417, 
            30.5417), Longs = c(-20.5254, -20.5254), N = c(150, 90), n = c(30, 
            50), c_id = c(4142, 4142)), .Names = c("year", "ID", "Lats", 
            "Longs", "N", "n", "c_id"), row.names = c(NA, -2L), 
            class = "data.frame")
dt <- data.table(df)
dt[, lapply(.SD, sum), by="c_id,year,ID,Lats,Longs"]

   c_id year  ID    Lats    Longs   N  n
1: 4142 2015 200 30.5417 -20.5254  240 80

Solution using plyr:

require(plyr)
ddply(df, .(c_id, year, ID, Lats, Longs), function(x) c(N=sum(x$N), n=sum(x$n)))

  c_id year  ID    Lats    Longs   N  n
1 4142 2015 200 30.5417 -20.5254 240 80
Tuesday, November 29, 2022
3

You can do it like this, do the calculation from the innermost of the array. Check the demo.

<?php
function f(&$array)
{
    foreach($array as $k => &$v)
    {
        if(is_array($v))
        {
            if(count($v) == count($v, 1))
            {
                unset($array[$k]);
                if($k == 'sum')
                {
                    $v =  array_sum($v);
                    $array[] = $v;

                }elseif($k == 'multiply'){
                    $v = array_product($v);
                    $array[] = $v;
                }else{

                    foreach($v as $vv)
                        $array[] = $vv;
                }
            }else
                f($v);
        }
    }
}

while(count($array) != count($array, 1))
{
    f($array);
}

print_r($array);

Note:

traverse array from outer to inner
traverse array from inner to outer

Monday, November 14, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :