phparraysmultidimensional-arraypivotgrouping

Pivot 2d array data by two columns and use zero default values for any gaps in data


This is the result of array after I build it using the array_push() function from mssql result.

Array
(
    [0] => Array
        (
            [STICKER] => FALCON
            [MONTH] => 1
            [JUM] => 65826210.00
        )

    [1] => Array
        (
            [STICKER] => FALCON
            [MONTH] => 2
            [JUM] => 68070573.00
        )

    [2] => Array
        (
            [STICKER] => FALCON
            [MONTH] => 3
            [JUM] => 99053067.60
        )

    [3] => 
    [4] => Array
        (
            [STICKER] => HRD
            [MONTH] => 2
            [JUM] => 1521400.00
        )

    [5] => Array
        (
            [STICKER] => HRD
            [MONTH] => 3
            [JUM] => 2093200.00
        )
)

I need to convert array above into this structure:

Array
(
    [0] => Array
        (
            [0] => 
            [1] => 1
            [2] => 2
            [3] => 3
        )
    [1] => Array
        (
            [0] => FALCON
            [1] => 65826210.00
            [2] => 68070573.00
            [3] => 99053067.60
        )
    [2] => Array
        (
            [0] => HRD
            [1] => 0
            [2] => 1521400.00
            [3] => 2093200.00
        )
)

Note: Array[0] values would be 1,2,3 (this is actualy month, i just input up to 3 in order to get the code not too long. but it will be up to 12 (Jan - Dec)).

If from original array, there is none value (example from array[3]), then it will be convert to new array[2]->[1] with value 0.


Solution

  • try something like this not the issue with the empty array i could not understand how the program would know that it is STICKER HRD so it will be filled with zero.But you could later check if every month "isset" and if it is not act as it is zero

    $arr1=array(
     array('STICKER'=>'FALCON','MONTH'=>1,'JUM'=>65826210.00),
     array('STICKER'=>'FALCON','MONTH'=>2,'JUM'=>68070573.00),
     array('STICKER'=>'FALCON','MONTH'=>3,'JUM'=>99053067.60),
     array(),
     array('STICKER'=>'HRD','MONTH'=>2,'JUM'=>1521400.00),
     array('STICKER'=>'HRD','MONTH'=>3,'JUM'=>2093200.00),
    );
    
    $arr2=array();
    $arr3=array();
    
    $arr2[0][0]="";
    foreach($arr1 as $key => $val){
     if(!empty($val)){
        $arr2[0][$val['MONTH']]=$val['MONTH'];
    
        //group each STICKER
        $arr3[$val['STICKER']][]=$val['JUM'];
     }
    }
    
    //transfer the grouped data to arr2
    foreach($arr3 as $key => $val){
    
     $tmp_arr=array($key);
    
      $arr2[]=array_merge($tmp_arr,$val);
    }
    
    
    print_r($arr2);