我目前在阵列中有数组括号。即$variable[other[0]] = "something"
我想要一个小函数,它将检查$ variable并查看是否有括号。如果有括号,则删除该部分并将其添加为多维数组。这可能吗?谢谢!
例如:
$variable = array(
'test' => "test",
'what' => "something else",
'here[0]' => "yeah",
'here[1]' => "weee"
);
print_r($variable);
这将输出:
Array ( [test] => test [what] => something else [here[0]] => yeah [here[1]] => weee )
但是,我希望它运行一个正则表达式函数并拆分任何带括号的东西并将其转换为多维数组。
这将是预期的输出:
Array ( [test] => test [what] => something else [here] => Array ( [0] => yeah [1] => weee ) )
答案 0 :(得分:0)
您可以使用http_build_query和parse_str以及
$variable = array(
'test' => "test",
'what' => "something else",
'here[0]' => "yeah",
'here[1]' => "weee"
);
$string = http_build_query($variable);
parse_str($string, $array);
var_dump($array);
答案 1 :(得分:0)
这应该有效:
foreach ($variable as $key => $val) {
preg_match_all('/\[([A-Za-z0-9 ]+?)\]/', $key, $out);
if (!empty($out[0])) {
$chopped = str_replace($out[0][0], "", $key);
$innerkey = $out[1][0];
$variable[$chopped][$innerkey] = $val;
unset($variable[$key]);
}
}