3v4l.org

run code in 300+ PHP versions simultaneously
<?php ########### SIMULATE DATABASE INSERTED DATA ############ $apple = new stdClass; $apple->id = 1; $apple->name = "Apple"; $banana = new stdClass; $banana->id = 2; $banana->name = "Banana"; $carrot = new stdClass; $carrot->id = 3; $carrot->name = "Carrot"; $dill = new stdClass; $dill->id = 4; $dill->name = "Dill"; $egg = new stdClass; $egg->id = 5; $egg->name = "Egg"; $fred = new stdClass; $fred->id = 6; $fred->name = "Fred"; $goat = new stdClass; $goat->id = 7; $goat->name = "Goat"; $harry = new stdClass; $harry->id = 8; $harry->name = "Harry"; $obj_array[] = $harry; $igloo = new stdClass; $igloo->id = 9; $igloo->name = "Igloo"; $jason = new stdClass; $jason->id = 10; $jason->name = "Jason"; $klaus = new stdClass; $klaus->id = 11; $klaus->name = "Klaus"; $apple->link = array($banana, $egg); $banana->link = array($carrot); $carrot->link = array($apple, $banana, $carrot); $dill->link = array($apple, $egg); $egg->link = array($fred); $fred->link = array($goat); $goat->link = array($goat, $harry); $igloo->link = array($banana, $egg); $jason->link = array($apple, $egg, $harry); $klaus->link = array($apple, $egg); ################### END OF DATABASE INSERTS ############## function processObjNetwork(stdClass $rootObj){ $linkedObjects = array(); $process = function(stdClass $obj) use(&$linkedObjects, &$process){ if(isset($linkedObjects[$obj->id])) return; else $linkedObjects[$obj->id] = $obj; if(empty($obj->link)) return; foreach($obj->link as $child) $process($child); }; $process($rootObj); return $linkedObjects; } $linkedObjects = processObjNetwork($apple); foreach($linkedObjects as $obj) echo "$obj->name \n";
Output for 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 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.30, 8.2.0 - 8.2.25, 8.3.0 - 8.3.13
Apple Banana Carrot Egg Fred Goat Harry

preferences:
92.77 ms | 407 KiB | 5 Q