Last active
December 21, 2020 02:24
-
-
Save tanftw/8f159fec2c898af0163f to your computer and use it in GitHub Desktop.
Array Unflatten with PHP
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 | |
if ( ! function_exists( 'array_unflatten' ) ) | |
{ | |
/** | |
* Convert flatten collection (with dot notation) to multiple dimmensionals array | |
* @param Collection $collection Collection to be flatten | |
* @return Array | |
*/ | |
function array_unflatten( $collection ) | |
{ | |
$collection = (array) $collection; | |
$output = array(); | |
foreach ( $collection as $key => $value ) | |
{ | |
array_set( $output, $key, $value ); | |
if ( is_array( $value ) && ! strpos( $key, '.' ) ) | |
{ | |
$nested = array_unflatten( $value ); | |
$output[$key] = $nested; | |
} | |
} | |
return $output; | |
} | |
} | |
// From Laravel | |
if ( ! function_exists( 'array_set' ) ) | |
{ | |
function array_set( &$array, $key, $value ) | |
{ | |
if ( is_null( $key ) ) | |
return $array = $value; | |
$keys = explode( '.', $key ); | |
while ( count( $keys ) > 1 ) | |
{ | |
$key = array_shift( $keys ); | |
// If the key doesn't exist at this depth, we will just create an empty array | |
// to hold the next value, allowing us to create the arrays to hold final | |
// values at the correct depth. Then we'll keep digging into the array. | |
if ( ! isset( $array[$key] ) || ! is_array( $array[$key] ) ) | |
{ | |
$array[$key] = array(); | |
} | |
$array =& $array[$key]; | |
} | |
$array[array_shift( $keys )] = $value; | |
return $array; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment