3v4l.org

run code in 300+ PHP versions simultaneously
<?php $data = [ [ 'table' => 'test', 'parent_table' => NULL, ], [ 'table' => 'test', 'parent_table' => NULL, ], [ 'table' => 'test2', 'parent_table' => 'test', ], [ 'table' => 'test4', 'parent_table' => NULL, ], [ 'table' => 'test5', 'parent_table' => 'test3', ], [ 'table' => 'test6', 'parent_table' => 'test5', ], [ 'table' => 'test3', 'parent_table' => 'test', ], ]; function reorderHierarchy($data){ $hierarchy = []; $top_level_parents = []; foreach($data as $each_data){ $hierarchy[$each_data['table']] = array(); if(is_null($each_data['parent_table'])){ if(!isset($top_level_parents[$each_data['table']])){ $top_level_parents[$each_data['table']] = 0; } $top_level_parents[$each_data['table']]++; } } foreach($data as $each_data){ if(!is_null($each_data['parent_table'])){ $hierarchy[$each_data['parent_table']][] = $each_data['table']; } } $result = []; traverseHierarchy($hierarchy,$top_level_parents,$result); return $result; } function traverseHierarchy($hierarchy,$top_level_parents,&$result){ foreach($top_level_parents as $each_parent => $occurrences){ while($occurrences-- > 0){ $result[] = [ 'table' => $each_parent, 'parent_table' => NULL ]; } traverseChildren($hierarchy,$each_parent,$result); } } function traverseChildren($hierarchy,$parent,&$result){ foreach($hierarchy[$parent] as $each_child){ $result[] = [ 'table' => $each_child, 'parent_table' => $parent ]; traverseChildren($hierarchy,$each_child,$result); } } foreach(reorderHierarchy($data) as $each_data){ echo $each_data['table']," , ",(is_null($each_data['parent_table']) ? "NULL" : $each_data['parent_table']),PHP_EOL; }
Output for 7.1.25 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.28, 8.4.1 - 8.4.14, 8.4.16, 8.5.0 - 8.5.1
test , NULL test , NULL test2 , test test3 , test test5 , test3 test6 , test5 test4 , NULL
Output for 8.4.15
/bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.35' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.34' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15)
Process exited with code 1.

preferences:
188.44 ms | 407 KiB | 5 Q