我想将HTML样式的表单数组转换为PHP数组。 我尝试了很多解决方案,但我只得到错误或引用(“指针”)问题。
HTML数组pathes的格式如下:
tree[]
tree2[key1]
tree2[key2][key3]
tree3[][key4]
这是构建数组的方法,我删除了不起作用的代码(因为它只是垃圾):
private function addFieldToBag(BagCollectionInterface $bag, $name, $content)
{
# The field is not an array component
if(!$firstKey = strpos($name, '['))
{
$bag->add($name, $content);
}
# The field is part of an array (eg. "tree[key][]")
else
{
preg_match_all('/(?:\\[(\\w*)\\])/', $name, $treeComponents);
# $treeComponents[1] = ['key', ''], will be used to build the array
$treeRootName = substr($name, 0, $firstKey);
# $treeRootName = 'tree'
# eg. "tree" array doesn't exists yet
if(!array_key_exists($treeRootName, $bag->all()))
{
$treeRoot = [];
}
else
{
$treeRoot = $bag->get($treeRootName);
}
# Here I want to build the array using :
# $treeRoot as the array root, containing data or not.
# $treeComponents[1] as the path to build
# $content as the final scalar value of the path
# eg. on tree[][key] with value of 'scalarValue':
# $treeRoot = [
# 0 => [
# key => scalarValue
# ]
# ]
# Reassignation of the array to the bag,
# because I can not modify the array returned by $bag->get(name); :(
$bag->add($treeRootName, $treeRoot);
}
}
我很失落,谢谢你的帮助。