Last active
April 12, 2023 09:06
-
-
Save carolosf/66dcbcf7e9063528f8cc518e57e2c3b4 to your computer and use it in GitHub Desktop.
Explode To Nested Array - Converts a string with a delimiter into a nested associative array and assigns the value to the final key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Converts a string with a delimiter into a nested associative array and assigns the value to the final key | |
* by Carolos Foscolos - I call this little algorithm bubble wrap - because it's like wrapping bubbles around each other | |
* explodeToNestedArray('.', 'abc.def', 'XYZ') becomes ['abc' => ['def' => 'XYZ']] | |
* | |
* @param string $delimiter | |
* @param string $key | |
* @param $value | |
* | |
* @return array { | |
* @var string Field names | |
* @var mixed Values relating to fields. | |
* } | |
*/ | |
function explodeToNestedArray($delimiter, $key, $value) | |
{ | |
$keys = explode($delimiter, $key); | |
while ($key = array_pop($keys)) { | |
$value = [$key => $value]; | |
} | |
return $value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment