Passing an Array Key to a variable

时间:2019-01-18 18:34:06

标签: php multidimensional-array

I have a script which puts products into a shopping cart;

if (isset($_POST["top"])) {
    $name = $_POST["name"];

    $_SESSION[$$name] += 1;

    $$name = $_SESSION[$$name];
    $name = $name.$$name;

    $piid = $_SESSION["piid"];
    $prod = $_POST["prod"];

    $_SESSION["cart"][$name] = array("id" => $prod, "name" => $_POST["name"], "quantity" => 1, "des" => $_POST["des"]);
    foreach ($piid as $value) {
        $ab = $value[id];
        $qty = $_POST["htop".$ab];

        if ($qty > 0) {
            $piid[] = array("id" => $row["ID"], "des" => $row["des"], "hid" => $row["hide"]);

            $_SESSION["cart"][$name]["top".$value[id]] = array("id" => $value[id], "dec" => $value[des], "qty" => $qty);
        }
    }
} else {
    $name = $_POST["name"];

    $name = $name.$$name;
    if (isset($_SESSION['cart'][$name]) && ($_SESSION['cart'][$name]['des'] === $_POST['des'])) {
        $_SESSION['cart'][$name]['quantity'] += 1;
    } elseif (isset($_SESSION['cart'][$name]) && ($_SESSION['cart'][$name]['des'] <> $_POST['des'])) {
        $_SESSION[$$name] += 1;

        $name = $_SESSION[$$name];
        $_SESSION["cart"][$name] = array("id" => $_POST["prod"], "name" => $_POST["name"], "quantity" => 1, "des" => $_POST["des"]);
    } else {
        $_SESSION["cart"][$name] = array("id" => $_POST["prod"], "name" => $_POST["name"], "quantity" => 1, "des" => $_POST["des"]);
    }
}

To avoid confusion in the array when items have different description it will set a multi-dimensional array by using the product's name and an incremental id (where required)

Now my question is how do I get a remove button to work something like this? I need to pass that sub-array's name/key as a variable so we can then pass that back to the POST method.

echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post" 
   enctype="application/x-www-form-urlencoded">
<button type="submit">Remove
<input type="hidden" name="rprid" value="' .$name. '" />
<button</form></div>

Thanks!

1 个答案:

答案 0 :(得分:0)

我设法弄清楚了我需要的代码,应该是下面的代码;

foreach($cart as $key => $value)
    {
        echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post" enctype="application/x-www-form-urlencoded"><button type="submit">Remove<input type="hidden" name="rprid" value="' .$key. '" /></form></div>';
}

感谢所有的想法!

编辑:解决方案是使用$key => $value这样,您可以简单地使用$ key返回您正在查看的密钥。