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);
Output for 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.4, 8.3.6 - 8.3.27, 8.4.1 - 8.4.14
{ "Business Services": { "Consulting": "Consulting", "Foodservice Distribution": "Foodservice Distribution", "Information Services": "Information Services" }, "Consumer": { "Consumer Discretionary": { "Apparel, Footwear & Accessories": { "Activewear": "Activewear", "Apparel": "Apparel", "Footwear": "Footwear" } } } }
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 { "Business Services": { "Consulting": "Consulting", "Foodservice Distribution": "Foodservice Distribution", "Information Services": "Information Services" }, "Consumer": { "Consumer Discretionary": { "Apparel, Footwear & Accessories": { "Activewear": "Activewear", "Apparel": "Apparel", "Footwear": "Footwear" } } } }

preferences:
157.58 ms | 409 KiB | 5 Q