<?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));
You have javascript disabled. You will not be able to edit any code.