phparraysmultidimensional-arraygroupinghierarchical-data

Group rows of a multidimensional array to create hierarchical keys from 2 columns then create subarrays from non-identifying data


I have a PHP array like this and I want to group them per created_month and seq, I have tried merge and other method but it's not working.

"data": [
    {
        "seq": "1",
        "created_month": "Aug",
        "descr": "[YOU] - Not Recieved",
        "paydescr": "Revenue",
        "amount": "205.85"
    },
    {
        "seq": "1",
        "created_month": "Jul",
        "descr": "[YOU] - Not Recieved",
        "paydescr": "Revenue",
        "amount": "176.82"
    },
    {
        "seq": "2",
        "created_month": "Aug",
        "descr": "[OT] - Not Recieved",
        "paydescr": "Commission",
        "amount": "74.19"
    },
    {
        "seq": "2",
        "created_month": "Jul",
        "descr": "[OT] - Not Recieved",
        "paydescr": "Commission",
        "amount": "63.71"
    }
]

and want to display it like this, this would group by created month and Seq

[{"data":[  
     {  
        "Aug":[  
           {  
     "1":[  
           { 
            "descr": "[YOU] - Not Received",
            "paydescr": "Revenue",
            "amount": "0.00"
            }
    ],
    "2":[  
           {"descr": "[YOU] - Not Received",
            "paydescr": "Revenue",
            "amount": "0.00"
            }
     ]
           }
        ]
     }
  ]

} ]


Solution

  • Use this php code:

    $data = '{"data": [{
        "seq": "1",
        "created_month": "Aug",
        "descr": "[YOU] - Not Recieved",
        "paydescr": "Revenue",
        "amount": "205.85"
    }, {
        "seq": "1",
        "created_month": "Jul",
        "descr": "[YOU] - Not Recieved",
        "paydescr": "Revenue",
        "amount": "176.82"
    }, {
        "seq": "2",
        "created_month": "Aug",
        "descr": "[OT] - Not Recieved",
        "paydescr": "Commission",
        "amount": "74.19"
    }, {
        "seq": "2",
        "created_month": "Jul",
        "descr": "[OT] - Not Recieved",
        "paydescr": "Commission",
        "amount": "63.71"
    }]}';
    
    $data = json_decode($data, true);
    $newArr = array();
    foreach($data['data'] as $k=>$v){
        $newArr[$v['created_month']][$v['seq']][] = array("descr"=>$v['descr'],"paydescr"=>$v['paydescr'],"amount"=>$v['amount']);
    }
    echo json_encode($newArr);