sum specific values in a multidimensional array (php)

前端 未结 4 872
醉话见心
醉话见心 2020-11-27 08:52

I got a multidimensional array like this:

Totalarray
(
[0] => Array
    (
        [city] => NewYork
        [cash] => 1000
    )

[1] => Array
           


        
相关标签:
4条回答
  • 2020-11-27 09:09

    Using any more than one loop (or looping function) to sum the values is inefficient.

    Here is a method that uses temporary keys to build the result array and then reindexes the result array after the loop terminates.

    Code: (Demo)

    $array=[
        ['city' => 'NewYork', 'cash' => '1000'],
        ['city' => 'Philadelphia', 'cash' => '2300'],
        ['city' => 'NewYork', 'cash' => '2000']
    ];
    
    foreach($array as $a){
        if(!isset($result[$a['city']])){
            $result[$a['city']] = $a;  // store temporary city-keyed result array (avoid Notices)
        }else{
            $result[$a['city']]['cash'] += $a['cash'];  // add current value to previous value
        }
    }
    var_export(array_values($result));  // remove temporary keys
    
    0 讨论(0)
  • 2020-11-27 09:12

    Use function array_reduce() to combine the items having the same city:

    $input = array(
        array('city' => 'NewYork',      'cash' => '1000'),
        array('city' => 'Philadelphia', 'cash' => '2300'),
        array('city' => 'NewYork',      'cash' => '2000'),
    );
    
    $output = array_reduce(
        // Process the input list
        $input,
        // Add each $item from $input to $carry (partial results)
        function (array $carry, array $item) {
            $city = $item['city'];
            // Check if this city already exists in the partial results list
            if (array_key_exists($city, $carry)) {
                // Update the existing item
                $carry[$city]['cash'] += $item['cash'];
            } else {
                // Create a new item, index by city
                $carry[$city] = $item;
            }
            // Always return the updated partial result
            return $carry;
        },
        // Start with an empty list
        array()
    );
    
    0 讨论(0)
  • 2020-11-27 09:14

    Try below code:

    <?php
    
    $arr = array(
            array('city' => 'NewYork', 'cash' => '1000'),
            array('city' => 'Philadelphia', 'cash' => '2300'),
            array('city' => 'NewYork', 'cash' => '2000'),
        );
    
    $newarray = array();
    foreach($arr as $ar)
    {
        foreach($ar as $k => $v)
        {
            if(array_key_exists($v, $newarray))
                $newarray[$v]['cash'] = $newarray[$v]['cash'] + $ar['cash'];
            else if($k == 'city')
                $newarray[$v] = $ar;
        }
    }
    
    print_r($newarray);
    


    Output:

    Array
    (
        [NewYork] => Array
            (
                [city] => NewYork
                [cash] => 3000
            )
    
        [Philadelphia] => Array
            (
                [city] => Philadelphia
                [cash] => 2300
            )
    
    )
    


    Demo:
    http://3v4l.org/D8PME

    0 讨论(0)
  • 2020-11-27 09:19

    Try this:

     $sumArray = array();
    
        foreach ($arrTotal as $k=>$subArray) {
    
            foreach ($subArray as $id=>$value) {
                $sumArray[$subArray['city']]+=$value;
            }
    
        }
    
        var_dump($sumArray);
    

    Output:

    array(2) {
      ["NewYork"]=>
      int(3000)
      ["Philadelphia"]=>
      int(2300)
    }
    
    0 讨论(0)
提交回复
热议问题