3v4l.org

run code in 300+ PHP versions simultaneously
<?php $arr = Array ( 0 => 'Accessories/Apron', 1 => 'Accessories/Banners', 2 => 'Accessories/Belts', 3 => 'Brand/Brand1', 4 => 'Brand/Brand2', 5 => 'Apparel/Men/Belts', 6 => 'Apparel/Men/Socks', 7 => 'Apparel/Women/Leggings' ); $result =[]; foreach($arr as $val){ $count = count(explode("/", $val)); $str = '{"' . str_replace('/', '":{"', $val) . '"}' . str_repeat("}", $count-1); $json = preg_replace("/(.*)(\{)(.*?)(\})/", "$1[$3]", $str); $result = array_merge_recursive($result, json_decode($json, true)); } Print_r($result);
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.26, 8.3.0 - 8.3.14, 8.4.1
Array ( [Accessories] => Array ( [0] => Apron [1] => Banners [2] => Belts ) [Brand] => Array ( [0] => Brand1 [1] => Brand2 ) [Apparel] => Array ( [Men] => Array ( [0] => Belts [1] => Socks ) [Women] => Array ( [0] => Leggings ) ) )

preferences:
69.96 ms | 408 KiB | 5 Q