PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php use Carbon\Carbon; $collection = collect(json_decode(<<<JSON [ { "group": "WHITE", "name": "John Doe", "sequence": 1 }, { "group": "WHITE", "name": "John Doe Jr", "sequence": 2 }, { "group": "BLUE", "name": "John Doe Sr", "sequence": 3 }, { "group": "BLUE", "name": "John Doe Again", "sequence": 4 }, { "group": "RED", "name": "Mr John Doe", "sequence": 5 }, { "group": "RED", "name": "Ms Joahnna Doe", "sequence": 6 }, { "group": "BLUE", "name": "Dr Johnny Doe", "sequence": 7 }, { "group": "RED", "name": "Sir John Doe", "sequence": 8 }, { "group": "RED", "name": "Sir John Doe Senior", "sequence": 9 }, { "group": "WHITE", "name": "Ms John Doe", "sequence": 10 } ] JSON )); var_export( $collection->reduce( function ($result, $obj) { static $previousGroup, $groupKey, $keyCounters = []; $group = $obj->group; $keyCounters[$group] ??= 0; unset($obj->group); if (!$previousGroup || $previousGroup !== $groupKey) { $groupKey = "$group " . (++$keyCounters[$group]); $previousGroup = $groupKey; } $result[$groupKey][] = $obj; return $result; } ) );
Show:  
Copy Clear