CodeIgniter Forums
Re-arranging array of array - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Re-arranging array of array (/showthread.php?tid=70229)



Re-arranging array of array - ciadvantage - 03-10-2018

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


RE: Re-arranging array of array - chisler - 03-11-2018

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']];
   }



RE: Re-arranging array of array - ciadvantage - 03-12-2018

This works !
Thank you


RE: Re-arranging array of array - chisler - 03-13-2018

No problem, hope it helps.