Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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 );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...