Jump to content

[SOLVED] Groupping one of the values of multi assoc array using another as group factor


jeffz2008

Recommended Posts

Groupping one of the value multi assoc array using another as group factor

 

I have this problem.

I must admit it has bested me - for now.

 

I have assoc multi-array passed by POST.

 

I would like to group [final_price] => value using [tax_class_id] => as grouping factor and possibly get results in an array.

Of course it has to be a dynamic process, as number of subarrays will change. Also [tax_class_id] =>  is not a contant and can be changed, deleted, added etc.

 

See sample below:

--------------------

1. What I have:

--------------------

Array (

          [0 ] => Array (

[id] => 840

[model] => DMCFS20EB

[quantity] => 1

[final_price] => 166.8

[tax_class_id] => 0

)

          [1] => Array (

[id] => 821

[model] => TH42PX80B

[quantity] => 1

[final_price] => 570.2042

[tax_class_id] => 7

)

          [2] => Array (

[id] => 614

[model] => SL1000

[quantity] => 2

[final_price] => 215.99

[tax_class_id] => 8

)

            [3] => Array (

[id] => 282

[model] => RDRHXD870

[quantity] => 1

[final_price] => 199.991395

[tax_class_id] => 7

)

            )

 

-----------------------------

2. what I'd like to get:

-----------------------------

-> subarrays groupped by [tax_class_id] =>

-> [final_price] => added for same [tax_class_id]s

 

Array (

            [1] => Array (

[tax_class_id] => 0

[final_price] => 166.8

)

            [2] => Array (

[tax_class_id] => 7

[final_price] => 770.19559

)

            [3] => Array (

[tax_class_id] => 8

[final_price] => 215.99

)

)

slightly different array structure, but easier to create and easy to get yours if absolutely necessary

$result = array();
foreach ($arr as $data)
{
    if (isset($result[$data['tax_class_id']]))
        $result[$data['tax_class_id']] += $data['final_price'];
    else
        $result[$data['tax_class_id']] = $data['final_price'];
}

 

-->

 

Array
(
    [0] => 166.8
    [7] => 770.195595
    [8] => 215.99
)


 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.