Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

php - get unique value from array and sum totals

From this Array() I want to grab the values of amount_total, shipping and partner and total them up by specific partner. So for example the partner=>2665 should have a amount_total of 41.79 + 55.95 and so on please help. I don't want to do it through SQL because I need the data as it is as well.

Array
(
    [0] => Array
    (
        [amount_total] => 41.79
        [amount_shipping] => 4.99
        [amount_partner] => 14.8
        [partner] => 2665
    )
    [1] => Array
    (
        [amount_total] => 55.95
        [amount_shipping] => 19.96
        [amount_partner] => 11
        [partner] => 2665
    )
    [2] => Array
    (
        [amount_total] => 51.96
        [amount_shipping] => 7.98
        [amount_partner] => 23.98
        [partner] => 51754
    )
    [3] => Array
    (
        [amount_total] => 24.55
        [amount_shipping] => 4.99
        [amount_partner] => 5.67
        [partner] => 11513
    )
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use PHP to achieve this, but this won't be necessary. The database can do this much more efficiently

I assume your current query looks something like this

SELECT
    `amount_total`,
    `amount_shipping`,
    `amount_partner`,
    `partner`
FROM
    `salesLeads`
WHERE
    [..]

MySQL gives you nice aggregate functions like SUM you can use with GROUP BY

SELECT
    SUM( `amount_total` ) AS `amount_total`,
    SUM( `amount_shipping` ) AS `amount_shipping`,
    SUM( `amount_partner` ) AS `amount_partner`.
    `partner`
FROM 
    `salesLeads`
WHERE
     [..]
GROUP BY
     `partner`

in your PHP script you access this the same way but it has the final numbers grouped and summarized by partner already

e.g.

if ($result = $mysqli->query($query)) {

    while ($row = $result->fetch_assoc()) {
        print_r( $row );
    }

    $result->close();
}

EDIT

Because you wanted a PHP solution, which again is more efficient than querying twice:

$partnerSums = array();
while ( $row = $result->fetch_assoc() ) {
     if ( !array_key_exists( $row['partner'], $partnerSums ) {
          $partnerSums[$row['partner']] = $row;
     } else {
          $partnerSums[$row['partner']]['amount_total'] += $row['amount_total'];
          $partnerSums[$row['partner']]['amount_shipping'] += $row['amount_shipping'];
          $partnerSums[$row['partner']]['amount_partner'] += $row['amount_partner'];
     }
}

print_r( $partnerSums );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...