0

I have the following array

Array (
    [0] => Array
        (
            [0] => ALFA
            [1] => 213
        )

    [1] => Array
        (
            [0] => ALFA
            [1] => 151
        )

    [2] => Array
        (
            [0] => ALFA
            [1] => 197
        )

    [3] => Array
        (
            [0] => BETA
            [1] => 167
        )

    [4] => Array
        (
            [0] => ZETA
            [1] => 254
        )

    [5] => Array
        (
            [0] => GAMA
            [1] => 138
        )

    [6] => Array
        (
            [0] => GAMA
            [1] => 213
        )

)

And I would like to group the key[0] of the subarray so I can see how many equal keys it has.

Something like that:

ALFA => 3
BETA => 1
EPSI => 1
GAMA => 2

I tried with array_count_values, but without success.

foreach ($array as $value) {
    echo '<pre>';
    print_r(array_count_values($value));
    echo '</pre>';
}

With that we have following result:

Array
(
    [ALFA] => 1
    [213] => 1
)

Array
(
    [ALFA] => 1
    [151] => 1
)
...
Array
(
    [GAMA] => 1
    [213] => 1
)

And after that I would like to sum the values of each group as well.

ALFA => 213 + 151 + 197
BETA => 167
ZETA => 254
GAMA => 138 + 213

I think that when we solve the first part of the problem, the second would follow easier with quite the same method.

The final purpose is to divide the sum of values by the number of occurrences of each key group, so we can have an average of the values just like that:

ALFA => (213+151+197) / 3 = 187
BETA => 167
ZETA => 254
GAMA => (138+213) / 2 = 175,5

This is not the main problem, but as I said, I'm stuck with the beginning of the solution and would appreciate any help.

ekad
  • 14,436
  • 26
  • 44
  • 46
Aloysia de Argenteuil
  • 833
  • 2
  • 11
  • 27

5 Answers5

2

I'm surprised at all the long and complicated answers. However, the initial foreach to model your data to something manageable is needed. After that you just need to do a really simple array_walk.

<?php
$result = array();
foreach ($array as $el) {
    if (!array_key_exists($el[0], $result)) {
        $result[$el[0]] = array();
    }
    $result[$el[0]][] = $el[1];
}
array_walk($result, create_function('&$v,$k', '$v = array_sum($v) / count($v);'));
?>

Result:

Array
(
    [ALFA] => 187
    [BETA] => 167
    [ZETA] => 254
    [GAMA] => 175.5
)
voldomazta
  • 1,300
  • 1
  • 10
  • 19
  • I got to hand it to others too for answering because they must've interpreted your words literally. English isn't my first language too so I thought about how I would state the problem and figured you just needed the average without all the other extra info. – voldomazta Sep 11 '14 at 19:52
0
$sort = array();
foreach ($array as $value) {
  $sort[$value[0]][] = $value[1];
}

then you count how many keys each has

$keys = array();
foreach($sort as $k => $v) {
  $keys[$k] = count($v);
}

then for calculating the amount

$sum = array();
$average = array();
foreach($sort as $k => $v) {
  $amount = 0;
  foreach($v as $val) {
    $amount += $val;
  }
  $sum[$k] = $amount; 
  $average[$k] = $amount / $keys[$k];
}

HOWEVER, If you want all the details in one array:

$final = array();
foreach ($array as $value) {
    $final[$value[0]]["values"][] = $value[1];
}
foreach($final as $k => $v) {
    $final[$k]["amount"] = count($v['values']);
    $amount = 0;
    foreach($v['values'] as $val) {
        $amount += $val;
    }
    $final[$k]["sum"] = $amount; 
    $final[$k]["average"] = $amount / $final[$k]["amount"];
}

example: http://jdl-enterprises.co.uk/sof/25789697.php

Includes Output

James Lalor
  • 1,236
  • 9
  • 22
0

Solution for you is here:

Code:

$input = [

    ['alfa', 123],
    ['alfa', 223],
    ['alfa', 122],
    ['alfa', 554],
    ['alfa', 34],
    ['dalfa', 123],
    ['halfa', 223],
    ['dalfa', 122],
    ['halfa', 554],
    ['ralfa', 34]
];

$result = [];

foreach ($input as $node) {
    if (isset($result[$node[0]])) {
        $result[$node[0]] = ['sum' => $result[$node[0]]['sum'] + $node[1], 'count' => $result[$node[0]]['count'] + 1];
    } else {
        $result[$node[0]] = ['sum' => $node[1], 'count' => 1];
    }
}

print_r($result);

foreach ($result as $key => &$data) {
    $data = $data['sum'] / $data['count'];
}

print_r($result);

Output:

Array
(
    [alfa] => Array
        (
            [sum] => 1056
            [count] => 5
        )

    [dalfa] => Array
        (
            [sum] => 245
            [count] => 2
        )

    [halfa] => Array
        (
            [sum] => 777
            [count] => 2
        )

    [ralfa] => Array
        (
            [sum] => 34
            [count] => 1
        )

)
Array
(
    [alfa] => 211.2
    [dalfa] => 122.5
    [halfa] => 388.5
    [ralfa] => 34
)
Lauri Orgla
  • 561
  • 3
  • 10
0

Just copy the codes to your favorite text editor, sure it works perfectly.

    $items = [
        ['ALFA',213],
        ['ALFA',151],
        ['ALFA',197],
        ['BETA',167],
        ['ZETA',254],
        ['GAMA',138],
        ['GAMA',213]
    ];

    echo '<pre>' . print_r($items,true) . '</pre>';

    $result;

    foreach ($items as $value) {
        # code...
        if (isset($result[$value[0]])) {
            $sum = $result[$value[0]]['sum'] + $value[1];
            $count =  $result[$value[0]]['count'] + 1;
            $result[$value[0]] = ['sum' => $sum  , 'count' => $count, 'divided' => ($sum / $count)];
        } else {
            $result[$value[0]] = ['sum' => $value[1] , 'count' => 1 , 'divided' => ($value[1] / 1) ];
        }
    }

    echo '<pre>' . print_r($result,true) . '</pre>';
Miks
  • 114
  • 8
0
$myArray = [
    ["ALFA",213],
    ["ALFA",151],
    ["ALFA",197],
    ["BETA",167],
    ["ZETA",254],
    ["GAMA",138],
    ["GAMA",213]
];
$a1 = array(); //TEMPORARY ARRAY FOR KEEPING COUNT & TOTAL VALUES
$res = array(); //ARRAY USED TO KEEP RESULT
foreach($myArray as $val)
{
    //AVOID PESKY NOTICES FOR UNDEFINED INDEXES
    if ( !array_key_exists($val[0],$a1) ) {
        $a1[$val[0]] = array("count" => 0,"total" => 0);
        $res[$val[0]] = 0;
    }
    //INCREMENT THE COUNT OF INSTANCES OF THIS KEY
    $a1[$val[0]]["count"]++;
    //INCREMENT THE TOTAL VALUE OF INSTANCES OF THIS KEY
    $a1[$val[0]]["total"]+=$val[1];
    // UPDATE RESULT ARRAY
    $res[$val[0]] = $a1[$val[0]]["total"] / $a1[$val[0]]["count"];
}

print_r($res);

Should result in:

Array
(
    [ALFA] => 187
    [BETA] => 167
    [ZETA] => 254
    [GAMA] => 175.5
)

Sample: http://phpfiddle.org/lite/code/a7nt-5svf

Dan Delaney
  • 353
  • 1
  • 5