3v4l.org

run code in 300+ PHP versions simultaneously
<?php $data = [ 0 => 'Business Services', 1 => 'Business Services_Consulting', 2 => 'Business Services_Foodservice Distribution', 3 => 'Business Services_Information Services', 4 => 'Consumer', 5 => 'Consumer_Consumer Discretionary', 6 => 'Consumer_Consumer Discretionary_Apparel, Footwear & Accessories', 7 => 'Consumer_Consumer Discretionary_Apparel, Footwear & Accessories_Activewear', 8 => 'Consumer_Consumer Discretionary_Apparel, Footwear & Accessories_Apparel', 9 => 'Consumer_Consumer Discretionary_Apparel, Footwear & Accessories_Footwear', ]; // Our output array $array = []; foreach ($data as $item) { // Store a reference to the "deepest" item (so far) $last = &$array; // Split on known delim and iterate over foreach (explode('_', $item) as $key) { // See next comment for what this does. if (!is_array($last)) { $last = []; } // Set a key to match the value exactly. If the value has "child" objects, the logic // above will take care of removing the value and replacing it with an array. if (!array_key_exists($key, $last)) { $last[$key] = $key; } // Reset our "deepest" item $last = &$last[$key]; } } echo json_encode($array, JSON_PRETTY_PRINT);

preferences:
26.32 ms | 405 KiB | 5 Q