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

I have this array:

Array (
  [0] => Array (
    [TaxeName] => TPS
    [TaxeAmount] => 7
    [Price] => 14
  )
  [1] => Array (
    [TaxeName] => TVQ
    [TaxeAmount] => 9.975
    [Price] => 10
  )
  [2] => Array (
    [TaxeName] => TVQ
    [TaxeAmount] => 9.975
    [Price] => 18
  )
)

How I can get another array:
- Grouping the TaxeName and the TaxeAmount and
- Making the sum of the amount Price ?

Like this:

Array (
  [0] => Array (
    [TaxeName] => TPS
    [TaxeAmount] => 7
    [Price] => 14
  )
  [1] => Array (
    [TaxeName] => TVQ
    [TaxeAmount] => 9.975
    [Price] => 28
  )
)
See Question&Answers more detail:os

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

1 Answer

Something like this maybe:

$final = array();
foreach ($arr as $subarr)
{
    if (!isset($final[$subarr['TaxeName']]))
    {
        $final[$subarr['TaxeName']] = array('Price' => 0);
    }
    $final[$subarr['TaxeName']]['TaxeName'] = $subarr['TaxeAmount'];
    $final[$subarr['TaxeName']]['TaxeName'] = $subarr['TaxeName'];
    $final[$subarr['TaxeName']]['Price'] = $final[$subarr['TaxeName']]['Price'] + $subarr['Price'];
}

The idea is to make a new array with the values that you need and initializing it with the price set to 0 so you can increment it in the foreach


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