Skip to content

Instantly share code, notes, and snippets.

@unfulvio
Created June 29, 2015 10:25
Show Gist options
  • Save unfulvio/e962bfb403a10fa96a51 to your computer and use it in GitHub Desktop.
Save unfulvio/e962bfb403a10fa96a51 to your computer and use it in GitHub Desktop.
Make a multidimensional array with keys from a string with a variable amount of key names placed between square brackets
<?php
/**
* Problem:
* Given a string similar to '[key][subkey][otherkey]'
* we want to make a multidimensional array $array['key']['subkey']['otherkey']
*
* Original question on Stackoverflow:
* @link http://stackoverflow.com/questions/31103719/php-make-a-multidimensional-associative-array-from-key-names-in-a-string-separat/31104168
* There are alternative solutions posted.
*/
$str = '[key][subkey][otherkey]';
$value = 'my_value';
$arr = [];
// Note: a different approach would be using explode() instead
preg_match_all( '/\[([^\]]*)\]/', $str, $has_keys, PREG_PATTERN_ORDER );
if ( isset( $has_keys[1] ) ) {
$keys = $has_keys[1];
$k = count( $keys );
if ( $k > 1 ) {
for ( $i=0; $i<$k-1; $i++ ) {
$arr[$keys[$i]] = walk_keys( $keys, $i+1, $value );
}
} else {
$arr[$keys[0]] = $value;
}
$arr = array_slice( $arr, 0, 1 );
}
var_dump( $arr );
function walk_keys( $keys, $i, $value ) {
$a = '';
if ( isset( $keys[$i+1] ) ) {
$a[$keys[$i]] = walk_keys( $keys, $i+1, $value );
} else {
$a[$keys[$i]] = $value;
}
return $a;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment