如何在多维数组中对相同的字段值求和

时间:2014-10-14 08:21:49

标签: php arrays sum

我必须承认,理解这些表对我来说是一个很大的挑战,所以请不要那么难以评判我......

这是我的阵列:

Array
(
    [names] => Array
        (
            [0] => Name1
            [1] => Name2
            [2] => Name1
        )

    [ids] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 1
        )

    [quantities] => Array
        (
            [0] => 255
            [1] => 2
            [2] => 467
        )

)

我希望总结一下" quantities"其中namesids相同。

示例输出应为:

Array
(
    [names] => Array
        (
            [0] => Name1
            [1] => Name2
        )

    [ids] => Array
        (
            [0] => 1
            [1] => 2
        )

    [quantities] => Array
        (
            [0] => 722
            [1] => 2
        )

)

我知道有一个像" array_reduce"但不知道如何使用它。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

试试这个

    $result = [];
    foreach($array['ids'] as $key=>$val ){

        if(array_key_exists($val, $result)){

            $result[$val]['sum_quantity'] += $array['quantities'][$key];
        }
        else{
            $result[$val]['sum_quantity'] = $array['quantities'][$key];
            $result[$val]['name'] = $array['names'][$key];
            $result[$val]['id'] = $array['ids'][$key];
        }
    }

和输出将是这样的

    Array
    (
        [1] => Array //array key = id
        (
            ['name'] => Name1,
            ['sum_quantity'] => 722,
            ['id'] => 1
        )

        [2] => Array
        (
            ['name'] => Name2,
            ['sum_quantity'] => 2,
            ['id'] => 2
        )
)

答案 1 :(得分:0)

你可以这样做:

    $testArray['names'][0]='name1';
    $testArray['names'][1]='name2';
    $testArray['names'][2]='name1';

    $testArray['ids'][0]=1;
    $testArray['ids'][1]=2;
    $testArray['ids'][2]=1;

    $testArray['quantities'][0]=255;
    $testArray['quantities'][1]=2;
    $testArray['quantities'][2]=467;

    echo "<pre>";

    print_r($testArray);

    $unqArray['names']=array();
    $unqArray['ids']=array();
    $unqArray['quantities']=array();

    foreach($testArray['ids'] as $key=>$value)
    {
        if(!in_array($value,$unqArray['ids']))
        {
            $unqArray['names'][]=$testArray['names'][$key];
            $unqArray['ids'][]=$testArray['ids'][$key];
            $quantity=0;
            foreach($testArray['ids'] as $keyId=>$valueId)
            {
                if($valueId==$value)
                {
                    $quantity+=$testArray['quantities'][$keyId];
                }
            }
            $unqArray['quantities'][]=$quantity;
        }
    }

    print_r($unqArray);

    echo "</pre>";