3v4l.org

run code in 300+ PHP versions simultaneously
<?php $input = array( array("id" => "Cosmetics", "parent" => "Beauty"), array("id" => "Makeup", "parent" => "Cosmetics"), array("id" => "Beauty", "parent" => null) ); $options = array(); $refs = array(); foreach($input as &$category) { $refs[$category["id"]] = $option = array( "id" => $category["id"], "options" => array() ); print_r($refs); if($category["parent"]){ if(!array_key_exists($category["parent"], $refs)) { $parent = array( "id" => $category["parent"], "options" => array( &$refs[$category["id"]] ) ); $refs[$parent["id"]] = &$refs[$parent["id"]]; } else { $refs[$category["parent"]]["options"][] = &$option; // print_r($refs[$category["parent"]]); } } else { $options[] = $refs[$category["id"]]; } } print_r($options);
Output for 5.5.0 - 5.5.35, 5.6.0 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.20, 7.2.0 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
Array ( [Cosmetics] => Array ( [id] => Cosmetics [options] => Array ( ) ) ) Array ( [Cosmetics] => Array ( [id] => Cosmetics [options] => Array ( ) ) [Beauty] => [Makeup] => Array ( [id] => Makeup [options] => Array ( ) ) ) Array ( [Cosmetics] => Array ( [id] => Cosmetics [options] => Array ( [0] => Array ( [id] => Beauty [options] => Array ( ) ) ) ) [Beauty] => Array ( [id] => Beauty [options] => Array ( ) ) [Makeup] => Array ( [id] => Makeup [options] => Array ( ) ) ) Array ( [0] => Array ( [id] => Beauty [options] => Array ( ) ) )

preferences:
190.74 ms | 407 KiB | 216 Q