如何对数组基键中的元素求和

how to sum element in array base key

我有这样的数组

[1001] => Array
        (
            [0] => 500
        )

    [1204] => Array
        (
            [0] => 750
        )

    [1202] => Array
        (
            [0] => 0
            [1] => 10000
            [2] => 138456
        )

    [1203] => Array
        (
            [0] => 300
        )



)

我想像这样将键中数组的每个元素求和到新输出

[1001] => Array
        (
            [0] => 500
        )
[1204] => Array
        (
            [0] => 750
        )
[1202] => Array
        (
            [0] => 148456

        )
[1203] => Array
        (
            [0] => 300
        )





)

谢谢!

您可以对数组的每个元素使用 array_map to apply array_sum

$sum_array = array_map(function ($v) { return array_sum($v); }, $array);
print_r($sum_array);

Demo on 3v4l.org

您可以使用下面的代码。祝你好运!

    $data=[
        1001 => [ 500],1024 => [750],1202 =>[0,10000,138456],1203=>[300]
    ];


    foreach($data as $key => $value){

            if(count($data[$key]) > 1){
                    $data[$key]=array_sum($data[$key]);
            }else{
                $data[$key] =$data[$key];
            }

    }