unf*_*vio 4 php regex arrays string multidimensional-array
我有一个字符串,括号中包含可变数量的键名,例如:
$str = '[key][subkey][otherkey]';
Run Code Online (Sandbox Code Playgroud)
我需要创建一个多维数组,该数组具有在字符串中表示的相同键($value这里只是一个不重要的字符串值):
$arr = [ 'key' => [ 'subkey' => [ 'otherkey' => $value ] ] ];
Run Code Online (Sandbox Code Playgroud)
或者如果您更喜欢这种其他符号:
$arr['key']['subkey']['otherkey'] = $value;
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想像对待字符串那样追加数组键,但据我所知,这是不可能的.我认为array_push()在这里没有帮助.起初我以为我可以使用正则表达式从字符串中获取方括号中的值:
preg_match_all( '/\[([^\]]*)\]/', $str, $has_keys, PREG_PATTERN_ORDER );
Run Code Online (Sandbox Code Playgroud)
但我只有一个没有任何层次结构的非关联数组,这对我没用.
所以我提出了以下几点:
$str = '[key][subkey][otherkey]';
$value = 'my_value';
$arr = [];
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;
}
Run Code Online (Sandbox Code Playgroud)
现在,这"工作"(如果字符串有不同数量的'键'),但对我来说它看起来很丑陋而且过于复杂.有一个更好的方法吗?
当我看到preg_*和这样一个简单的模式时,我总是担心.如果你对$ str的格式有信心,我可能会选择这样的东西
<?php
// initialize variables
$str = '[key][subkey][otherkey]';
$val = 'my value';
$arr = [];
// Get the keys we want to assign
$keys = explode('][', trim($str, '[]'));
// Get a reference to where we start
$curr = &$arr;
// Loops over keys
foreach($keys as $key) {
// get the reference for this key
$curr = &$curr[$key];
}
// Assign the value to our last reference
$curr = $val;
// visualize the output, so we know its right
var_dump($arr);
Run Code Online (Sandbox Code Playgroud)