3v4l.org

run code in 300+ PHP versions simultaneously
<?php $rows = [ ['cat' => 'guest', 'name' => 'name_one', 'y' => '2016', 'q' => '2', 'st' => 1], ['cat' => 'guest', 'name' => 'name_one', 'y' => '2017', 'q' => '3', 'st' => 2], ['cat' => 'guest', 'name' => 'name_two', 'y' => '2017', 'q' => '1', 'st' => 1], ['cat' => 'guest', 'name' => 'name_two', 'y' => '2017', 'q' => '2', 'st' => 2], ]; $data = []; foreach ($rows as $row) { $link = &$data; foreach (['cat', 'name', 'y'] as $field) { if (!isset($link[$field])) $link[$field] = []; if (!isset($link[$field][$row[$field]])) $link[$field][$row[$field]] = []; $link = &$link[$field][$row[$field]]; } $link[] = ['q' => $row['q'], 'st' => $row['st']]; unset($link); } echo json_encode($data);

preferences:
34.61 ms | 458 KiB | 5 Q