Friday, April 20, 2012

PHP - Group Array by Key Value

Trying to group an array depending on whether it's index is divisible by there. I've tried various combinations of for loops and foreach loops and if($i % 3 == 0) ... But, it's not outputting the way I need it.



Here is a greatly simplified array (the original data contains a lot of highly sensitive information...)



The original array looks similar to this:



$item[0]['Section 1']['Item 2'] => 1334;
$item[1]['Section 2']['Item 3'] => 15454;
$item[2]['Section 3']['Item 4'] => 1452;
$item[3]['Section 4']['Item 5'] => 1341;
$item[4]['Section 5']['Item 6'] => 1788655;
$item[5]['Section 6']['Item 7'] => 13;
$item[6]['Section 7']['Item 8'] => 142;
$item[7]['Section 8']['Item 9'] => 15678;
$item[8]['Section 9']['Item 10'] => 15542;
$item[9]['Section 10']['Item 11'] => 16578;
$item[10]['Section 11']['Item 12'] => 18452;
$item[11]['Section 12']['Item 13'] => 16565;


I'm trying to group every 3 records, like this:



$newitem[0]['Section 1']['Item 2'] => 1334;
$newitem[0]['Section 2']['Item 3'] => 15454;
$newitem[0]['Section 3']['Item 4'] => 1452;
$newitem[1]['Section 4']['Item 5'] => 1341;
$newitem[1]['Section 5']['Item 6'] => 1788655;
$newitem[1]['Section 6']['Item 7'] => 13;
$newitem[2]['Section 7']['Item 8'] => 142;
$newitem[2]['Section 8']['Item 9'] => 15678;
$newitem[2]['Section 9']['Item 10'] => 15542;
$newitem[3]['Section 10']['Item 11'] => 16578;
$newitem[3]['Section 11']['Item 12'] => 18452;
$newitem[3]['Section 12']['Item 13'] => 16565;




No comments:

Post a Comment