PHP,发送带有2个字段的数组作为输入,通过Form隐藏

时间:2018-06-28 15:45:44

标签: php arrays

我有这个数组$ newArray,它是在POST表单内部构建的,所以我想将整个数组作为隐藏发送给INPUT:

Array
(
    [0] => Array
        (
            [day1to7] => 1
            [timeHHMM] => 10:00
        )

    [1] => Array
        (
            [day1to7] => 1
            [timeHHMM] => 11:00
        )

    [2] => Array
        (
            [day1to7] => 1
            [timeHHMM] => 12:00
        )

    [3] => Array
        (
            [day1to7] => 5
            [timeHHMM] => 14:00
        )

)

您能帮我知道如何用INPUT编写吗?

echo '<input type="hidden" name="newArraySend" value="'. $newArray[day1to7]['timeHHMM'] . '">';  -> this is my wrong try

而且,请让我知道我怎么能收到它?

$newArrayReceived = $_POST['newArraySend']; ->this also is wrong I think

非常感谢您, 费利佩

1 个答案:

答案 0 :(得分:2)

回答特定问题;您可以循环并添加隐藏的输入:

foreach($newArray as $key => $val) {
    echo '<input type="hidden" name="newArraySend['.$key.'][day1to7]" value="'.$val['day1to7'].'">';
    echo '<input type="hidden" name="newArraySend['.$key.'][timeHHMM]" value="'.$val['timeHHMM'].'">';
}

然后,接收方的PHP应该像使用原始数组一样使用$_POST['newArraySend']

或者只是编码整个数组:

$val = htmlentities(json_encode($newArray));
echo '<input type="hidden" name="newArraySend" value="'.$val.'">';

然后在接收端解码:

$result = json_decode(html_entity_decode($_POST['newArraySend']), true);

但实际上,使用会话可能会更好:

session_start();
$_SESSION['newArray'] = $newArray;

然后在接收端:

session_start();
$result = $_SESSION['newArray'];