简体   繁体   中英

Passing an associative array as value for a checkbox form (PHP)

I'm a new member on this site, though I've used it plenty before. I searched a bit for an answer to my question, but I can't seem to find one. So I figured I'll post on here.

Anyway, on to the question. In my code, what I want to do is create an associative array, and then somehow pass that value through $_POST. My most recent idea is to create the associative array, then use json_encode to a string, pass that string as the value for a checkbox and then, get the string value through $_POST and use json_decode to get that associative array.

So say I have an associate array called $array. I would encode it like so:

$string = json_encode($array)

Then I pass the string as the value for the checkbox:

<input type='checkbox' name='array[]' value='$string'>

Then, once the form is submitted, it gets the associatives array(s) and updates some $_SESSION values:

foreach ($_POST['array'] as $element)
{
    $array = json_decode($element,true);
    array_push($_SESSION['array'], $array);
    $_SESSION['sum'] = $_SESSION['sum'] + $array["price"];
}

However, I get a fatal error everytime this runs, something along the lines of "Unsupported operand types" referring to the line with $_SESSION['sum']. I also get an error whenever I try to see values of the array as well (eg echo $array["price"] or echo $array["size"]), with those errors being "Array to string conversion".

Anyone have any ideas? I'm pretty new to PHP (just started learning it this week, if you couldn't tell)

尝试使用此复选框呈现:

<input type='checkbox' name='array[]' value="<?php echo $string; ?>">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM