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);

preferences:
51.65 ms | 402 KiB | 5 Q