Jump to content

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


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
)


 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.