按字段分组数组并给出总值

时间:2015-04-12 14:48:22

标签: php arrays

我试图通过'标签'对以下数组进行分组。给每个人一个总价值。

Array
(
 [0] => Array
    (
        [label] => John
        [value] => 84
    )

 [1] => Array
    (
        [label] => Darren
        [value] => 28
    )

 [2] => Array
    (
        [label] => John
        [value] => 20
    )

 [3] => Array
    (
        [label] => Morgan
        [value] => 20
    )

 [4] => Array
    (
        [label] => Hannah
        [value] => 14
    )

 [5] => Array
    (
        [label] => Morgan
        [value] => 14
    )

 [6] => Array
    (
        [label] => Darren
        [value] => 10
    )
)

这将是最终结果:

Array
(
 [0] => Array
    (
        [label] => John
        [value] => 104
    )

 [1] => Array
    (
        [label] => Darren
        [value] => 38
    )

 [2] => Array
    (
        [label] => Morgan
        [value] => 34
    )

 [3] => Array
    (
        [label] => Hannah
        [value] => 14
    )
)

我假设我需要使用foreach将标签组合在一起,但我仍然坚持最好的方法。

2 个答案:

答案 0 :(得分:1)

我会做这样的事情(期待$array中的数组):

// output array
$newArray = array();

// loop over the input array
foreach($array as $entry) {
    // loop over the output array
    foreach($newArray as &$currentEntry) {
        // check if there is a the current label
        if($currentEntry['label'] == $entry['label']) {
            // if so, add the value and continue (also parent)
            $currentEntry['value'] += $entry['value'];
            continue 2;
        }
    }
    // if the current label wan't found, it will get here and add an entry
    array_push($newArray,$entry);
}

print_r($newArray);

答案 1 :(得分:1)

试试这个:

<?php

$array = [
    ['label' => 'John',
    'value' => '84'],
    ['label' => 'Darren',
    'value' => '28'],
    ['label' => 'John',
    'value' => '20'],
    ['label' => 'Morgan',
    'value' => '20'],
    ['label' => 'Hannah',
    'value' => '14'],
    ['label' => 'Morgan',
    'value' => '14'],
    ['label' => 'Darren',
    'value' => '10']
];

$final = [];
foreach ($array as $arr)
    $final[$arr['label']] = isset($final[$arr['label']]) ? $final[$arr['label']] + $arr['value'] : $arr['value'];
$result = [];
foreach ($final as $label => $value)
    $result[] = ['label' => $label, 'value' => $value];

print_r($result);

Output

Array
(
    [0] => Array
        (
            [label] => John
            [value] => 104
        )

    [1] => Array
        (
            [label] => Darren
            [value] => 38
        )

    [2] => Array
        (
            [label] => Morgan
            [value] => 34
        )

    [3] => Array
        (
            [label] => Hannah
            [value] => 14
        )

)