PHPで動的n次元配列追加をしたいです。 例え… - Qiita
function parse($s)
{
$a = null;
while ($s = preg_replace_callback('/(\w*)\((\w*)\)/', function($matches) use (&$a) {
list(, $k, $v) = $matches;
$k = empty($k) ? 0 : $k;
$a = empty($v) ? [$k => $a] : [$k => [$v]];
}, $s));
return $a;
}
assert(parse('a((b((c))))') === ['a' => [['b'=>[['c']]]]]);
assert(parse('(c)') === [['c']]);
assert(parse('b(c)') === ['b' => ['c']]);
function parse($s)
{
$a = null;
while ($s = preg_replace_callback('/(\w*)\((\w*)\)/', function($matches) use (&$a) {
list(, $k, $v) = $matches;
$a = array_values(array_filter(empty($v) ? [$k, $a] : [$k, [$v]]));
}, $s));
return $a;
}
assert(parse('a((b((c))))') === ['a', [['b', [['c']]]]]);
assert(parse('(c)') === [['c']]);
assert(parse('b(c)') === ['b', ['c']]);