3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?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);
based on 9RCf7
Output for 5.5.0 - 7.3.0beta1
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 ( ) ) )