3v4l.org

run code in 500+ PHP versions simultaneously
<?php declare(strict_types=1); $input = [ 'item/id' => 'my_id', 'item/title' => 'my_title', 'item/group1/val1' => 'my_val1', 'item/group1/val2' => 'my_val2', 'summary' => 'xyz', 'item/group1/val3' => 'my_val3', ]; function normalizeCategories(array $denormalizeCategories): array { $normalizedCategories = []; foreach ($denormalizeCategories as $stringCategories => $value) { $categories = explode('/', $stringCategories); $numCategories = count($categories); $pointer = &$normalizedCategories; for ($i = 0; $i < $numCategories; $i++) { $category = $categories[$i]; // Check if the category is the last one in the array. Case for only one category in the array. if ($i === $numCategories - 1) { $pointer[$category] = $value; } else { // If it is not the last category, ensure the category exists and is an array. if(!isset($pointer[$category]) || !is_array($pointer[$category])) { $pointer[$category] = []; } $pointer = &$pointer[$category]; } } unset($pointer); } return $normalizedCategories; } var_dump(normalizeCategories($input));
Output for master
array(2) { ["item"]=> array(3) { ["id"]=> string(5) "my_id" ["title"]=> string(8) "my_title" ["group1"]=> array(3) { ["val1"]=> string(7) "my_val1" ["val2"]=> string(7) "my_val2" ["val3"]=> string(7) "my_val3" } } ["summary"]=> string(3) "xyz" }

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
13.82 ms | 1164 KiB | 7 Q