通过POST通过隐藏输入传递多维数组

时间:2017-12-07 05:15:36

标签: php arrays post multidimensional-array

所以我在网上研究了如何传递一个我通过表单POST的数组。

这就是我的所作所为。

    $itemsArr = array();
    while ($row = $result->fetch_assoc()) {
    $totalPrice += $row['item_price'];
    $totalItemsOnCart += $row['quantity'];
    $itemId = $row['item_idPK'];
    $itemName = $row['item_name'];
    $itemPrice = $row['item_price'];
    $itemQty = $row['quantity'];
    $itemsArr[] = array($userId, $itemId, $itemQty);

    echo "<tr>";
    echo "<td>".$itemId."</td>";
    echo "<td>".$itemName."</td>";
    echo "<td>".$itemPrice."</td>";
    echo "<td>".$itemQty."</td>";
    echo "</tr>";   
    }

然后,我使用foreach循环迭代多维数组。

echo "<form class = 'BreadCode' action='Function_Cart.php' method='POST'>";
foreach($itemsArr as $value){
    print_r($value);
    echo '<input type="hidden" name="itemsArr[]" value="'. $value. '">';
}
    echo "<input type='hidden' name='userId' value='$userId'>";
    echo "<input type='hidden' name='itemId' value='$itemId'>";
    echo "<input type='hidden' name='quantity' value='$itemQty'>";
    echo "<input class='PayButton' type='submit' name='Btn-pay' value='Pay'>";
    echo "</form>";

我一直在&#34; Array to string conversion&#34; echo循环中隐藏输入的foreach()是否有错误

过去我还没有尝试通过array方法发送POST表单。我只是不知道如何解决这个问题。

以下是print_r()

的结果
Array ( [0] => 5112 [1] => 105 [2] => 2 ) 
Array ( [0] => 5112 [1] => 104 [2] => 1 )

请帮忙。

谢谢。

2 个答案:

答案 0 :(得分:1)

不需要放置foreach并增加执行时间。您只需使用json_encode

即可
echo "<form class = 'BreadCode' action='Function_Cart.php' method='POST'>";
echo '<input type="hidden" name="itemsArr" value="' . json_encode($itemsArr) . '">';

echo "<input type='hidden' name='userId' value='$userId'>";
echo "<input type='hidden' name='itemId' value='$itemId'>";
echo "<input type='hidden' name='quantity' value='$itemQty'>";
echo "<input class='PayButton' type='submit' name='Btn-pay' value='Pay'>";
echo "</form>";

答案 1 :(得分:0)

您只需要将数组编码为json并在操作页

上对其进行解码
echo '<input type="hidden" name="itemsArr" value="'.json_encode($itemsArr). '">';

在您的操作页面上解码它

$itemsArr = json_decode($_POST['itemsArr'],true)
相关问题