【问题标题】:Multidimensional associative array in $_POST returns only last value$_POST 中的多维关联数组仅返回最后一个值
【发布时间】:2025-12-23 00:55:12
【问题描述】:

我尝试创建一个多维关联数组,但 $_post 中只返回一个值。

查看工作示例:

<html>
<?php
    if (isset( $_POST['form_submit'])){
        $Step=$_POST['form_submit'];
        If ($Step>1) $Step=0;
    }else{
        $Step=0;
    }
switch ($Step) {
    case 0:
        echo '
        <form method="post">
        <input name="Txt[First]" type="text"/>
        <input name="Txt[First][Second]" type="text"/>
        <input name="Txt[First][Second][Third]" type="text"/>
        <input name="Txt[First][Second][Third][Fourth]" type="text"/>
        <button type="submit" name="form_submit" value="'.($Step+1).'">submit</button>
        </form>';
    break;

    case 1:
        echo '<br/></br>print_r($_POST):<br/>';
        print_r($_POST);
    break;
}
?>
</html>

编辑

如果我在每个输入名称的末尾添加“[]”,我将拥有所有值,但方式错误:
$_POST 会像:

Array ( 
    [Txt] => Array ( 
        [First] => Array ( 
            [0] => one 
            [Second] => Array ( 
                [0] => two 
                [Third] => Array ( 
                    [0] => three 
                    [Fourth] => Array (
                        [0] => four 
                ) 
            ) 
        ) 
    ) 
)

但我需要类似的东西:

$_Post[First] => one  
$_Post[First][Second] => two  
$_Post[First][Second][Third] => three  

...等等

【问题讨论】:

  • 输出是什么?
  • 当然,因为你正在覆盖$_POST[Txt][First],它是一个字符串值,然后“附加”一个新键Second,因此用数组替换现有的字符串值......
  • 如果你想让那个字段的值“存活”键 Second 由于下一个字段而发生。
  • “我需要像 xml 之类的东西” - 你需要比这更具体一点......请编辑问题以包含一个适当的例子您想在 $_POST 中找到的数组结构。
  • 你说你需要的东西是不可能的。一个值不能既是字符串又是数组。

标签: php html arrays multidimensional-array superglobals


【解决方案1】:

你想要的都是不可能的。数组中只能有索引,但如果$_POST['Txt']['First'] 是像one 这样的字符串,那么它就不能是具有['Second'] 索引的数组。

您可以将每个级别的文本放在一个命名元素中:

    <form method="post">
    <input name="Txt[First][text]" type="text"/>
    <input name="Txt[First][Second][text]" type="text"/>
    <input name="Txt[First][Second][Third][text]" type="text"/>
    <input name="Txt[First][Second][Third][Fourth][text]" type="text"/>
    <button type="submit" name="form_submit" value="'.($Step+1).'">submit</button>
    </form>';

那么结果将是:

$_Post['Txt'][First]['text'] => one  
$_Post['Txt'][First][Second]['text'] => two  
$_Post['Txt'][First][Second][Third]['text'] => three  
$_Post['Txt'][First][Second][Third][Fourth]['text'] => three  

【讨论】:

  • 谢谢。这可能是唯一的方法