假设有使用数组样式名称发布的表单输入:
<input type="text" name="user[name]" value="John" />
<input type="text" name="user[email]" value="foo@example.org" />
<input type="checkbox" name="user[prefs][]" value="1" checked="checked" />
<input type="checkbox" name="user[prefs][]" value="2" checked="checked" />
<input type="text" name="other[example][var]" value="foo" />
然后$_POST
会像这样回来,print_r()
'd:
Array
(
[user] => Array
(
[name] => John
[email] => foo@example.org
[prefs] => Array
(
[0] => 1
[1] => 2
)
)
[other] => Array
(
[example] => Array
(
[var] => foo
)
)
)
目标是能够调用一个函数,如下所示:
$form_values = form_values($_POST);
这会返回一个关联数组,其键的类似于原始输入名称的样式:
Array
(
[user[name]] => John
[user[email]] => foo@example.org
[user[prefs][]] => Array
(
[0] => 1
[1] => 2
)
[other[example][var]] => foo
)
这一直非常具有挑战性,此时我的“车轮在泥浆中旋转”。 : - [
答案 0 :(得分:1)
我不确定为什么你需要这样做,但如果以下代码可以给你一个提示:
$testArray = array ( 'user' => array ( 'name' => 'John', 'email' => 'test@example.org', 'prefs' => array ( 0 => '1', ), ), 'other' => array ( 'example' => array ( 'var' => 'foo', ), ), );
function toPlain($in,$track=null)
{
$ret = array();
foreach ($in as $k => $v) {
$encappedKey = $track ? "[$k]" : $k; /* If it's a root */
if (is_array($v)) {
$ret = array_merge($ret,toPlain($v,$track.$encappedKey));
} else {
$ret = array_merge($ret,array($track.$encappedKey => $v));
}
}
return $ret;
}
print_r(toPlain($testArray));
答案 1 :(得分:1)
如果你想测试的话,我尝试了自己疯狂的做法。
<?php
function buildArray($input, &$output, $inputkey='')
{
foreach($input as $key => $value)
{
if(is_array($value))
{
if($inputkey != "")
{
$inputkey .= "[$key]";
buildArray($value, $output, $inputkey);
}
else
{
buildArray($value, $output, $key);
}
}
else
{
$output[$inputkey."[$key]"] = $value;
}
}
}
$output = array();
$input = array("user"=>array("name"=>"John","Email"=>"test.com","prefs"=>array(1,2)), "other"=>array("example"=>array("var"=>"foo")));
buildArray($input, $output);
print_r($output);
?>
我不知道大多数内置PHP函数的强大功能,因为我还没有学习它们,所以我提出了自己的递归方式。