What is the best approach to splitting a string into a multidimensional array in PHP while maintaining hierarchy?
When splitting a string into a multidimensional array in PHP while maintaining hierarchy, the best approach is to use a combination of explode() function and looping through the resulting array to build the multidimensional structure. By splitting the string based on a delimiter and then processing each part individually, you can maintain the hierarchy of the original string.
$string = "first|second|third|fourth";
$delimiter = "|";
$parts = explode($delimiter, $string);
$result = [];
$currentArray = &$result;
foreach ($parts as $part) {
$currentArray[$part] = [];
$currentArray = &$currentArray[$part];
}
print_r($result);
Keywords
Related Questions
- What function can be used to embed an existing image at a specific X/Y position in a graphic created using PHP?
- How can PHP scripts be optimized to efficiently analyze and interpret temperature data for trend forecasting?
- What is the purpose of using header(Location: ) in PHP and what are the potential pitfalls associated with it?