PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php $source = ' [ { "PRODUCT" : "BANANA", "BUY_PERIOD" : "202101", "SALES_PERIOD" : "202101", "PERCENT_OF_SALES" : "20" }, { "PRODUCT" : "BANANA", "BUY_PERIOD" : "202101", "SALES_PERIOD" : "202102", "PERCENT_OF_SALES" : "10" }, { "PRODUCT" : "BANANA", "BUY_PERIOD" : "202101", "SALES_PERIOD" : "202103", "PERCENT_OF_SALES" : "15" }, { "PRODUCT" : "BANANA", "BUY_PERIOD" : "202101", "SALES_PERIOD" : "202104", "PERCENT_OF_SALES" : "35" } ] '; $data = json_decode($source, true); $result = array_reduce( $data, function($res, $el) { if (isset($res[$el['PRODUCT'] . "-" . $el['BUY_PERIOD']])) { $res[$el['PRODUCT'] . "-" . $el['BUY_PERIOD']]['SALES_PERIOD'][$el['SALES_PERIOD']] = $el['PERCENT_OF_SALES']; } else { $res[$el['PRODUCT'] . "-" . $el['BUY_PERIOD']] = [ 'PRODUCT' => $el['PRODUCT'], 'BUY_PERIOD' => $el['BUY_PERIOD'], 'SALES_PERIOD' => [ $el['SALES_PERIOD'] => $el['PERCENT_OF_SALES'] ] ]; } return $res; }, $res ); var_export(array_values($result));
Show:  
Copy Clear