• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Re-arranging array of array

#1
Hi all,

I have this kind of  array of example, 

$data = array(
  array('name'=>'Test 1 Corp', 'serviced'=>'Visual help', 'price'=>'100.00' , 'serviced_date'=>'01/01/2018'),
  array('name'=>'Test 2 Corp', 'serviced'=>'Reading help', 'price'=>'50.00' , 'serviced_date'=>'01/2/2018'),
  array('name'=>'Test 1 Corp', 'serviced'=>'Visual help', 'price'=>'100.00','serviced_date'=>'01/02/2018'),
  array('name'=>'Test 3 Corp', 'serviced'=>'Visual help', 'price'=>'100.00', 'serviced_date'=>'01/10/2018'),
 array('name'=>'Test 1 Corp', 'serviced'=>'Misc help', 'price'=>'50.00'),
      //.... could be more
);

I need to reduce this array to this format like 

$reduced = array(
        'Test 1 Corp' =>array( 'Visual Help' =>2, 'Reading Help'=>1, 'Misc Help'=>1),
        'Test 2 Corp' =>array( 'Visual Help' =>0, 'Reading Help'=>1, 'Misc Help'=>0),
         'Test 3 Corp' =>array('Visual Help'=>1,  'Reading Help'=>0, 'Misc Help'=>0)
         //... could be more 
);


In fact reduced array is like a sum up of  all kinds services that belong to each company.

Any help is appreciated!

Thanks
Reply

#2
I've no idea how you are going to set the zero values but the below should display the totals for each 'serviced' type by company.

Code:
$data = array(
       array('name'=>'Test 1 Corp', 'serviced'=>'Visual help', 'price'=>'100.00' , 'serviced_date'=>'01/01/2018'),
       array('name'=>'Test 2 Corp', 'serviced'=>'Reading help', 'price'=>'50.00' , 'serviced_date'=>'01/2/2018'),
       array('name'=>'Test 1 Corp', 'serviced'=>'Visual help', 'price'=>'100.00','serviced_date'=>'01/02/2018'),
       array('name'=>'Test 3 Corp', 'serviced'=>'Visual help', 'price'=>'100.00', 'serviced_date'=>'01/10/2018'),
       array('name'=>'Test 1 Corp', 'serviced'=>'Misc help', 'price'=>'50.00'),
       //.... could be more
    );

   $reduced  = array();
   foreach($data as $company)
   {
     if (!array_key_exists($company['name'], $reduced)){
       $reduced[$company['name']] = array();
     }

     if (!array_key_exists($company['serviced'], $reduced[$company['name']])) {
       $reduced[$company['name']][$company['serviced']] = 0;
     }

     ++$reduced[$company['name']][$company['serviced']];
   }
Reply

#3
This works !
Thank you
Reply

#4
No problem, hope it helps.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2018 MyBB Group.