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);
Output for 5.6.38, 7.0.0 - 7.0.31, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.30, 7.4.0 - 7.4.23, 8.0.0 - 8.0.11, 8.1rc1
{"cat":{"guest":{"name":{"name_one":{"y":{"2016":[{"q":"2","st":1}],"2017":[{"q":"3","st":2}]}},"name_two":{"y":{"2017":[{"q":"1","st":1},{"q":"2","st":2}]}}}}}}

preferences:
83.08 ms | 460 KiB | 5 Q