【问题标题】:How can I delete data from my array with the key value?如何使用键值从数组中删除数据?
【发布时间】:2019-04-05 16:50:27
【问题描述】:

我试图从我的数组中的特定键中删除所有数据,但无法弄清楚为什么我的代码不起作用。我使用print_r 来检查代码是否有效,当我单击“删除”按钮时,我可以看到每个数组都打印了正确的值,但它没有从键中删除数据。

我当前的数组如下所示:

Array
(
    [0] => Array
        (
            [0] => S30813-Q100-X303
            [1] => 5
            [2] => Refurbished
        )

    [1] => Array
        (
            [0] => JX-1T1-LTU
            [1] => 8
            [2] => New
        )

)

我正在将数据输出到一个表中:

        for ($row = 0; $row < $totalcount; $row++) {
        echo "<tr>";
        for ($col = 0; $col < 3; $col++) {
            echo "<td>".$contents[$row][$col]."</td>";

            }
        for ($col = 0; $col < 1; $col++) {

            $del = $row;
            echo "<td><form action='' method='post'><input type='text' name='del' value=".$row."></input><input type='submit' name='deletepart' value='Remove'></input></form></td>";
        }
        echo "</tr>";
        }

前端:

我的 php 取消设置数组键(我猜问题出在哪里)是:

<?php 

    if (isset($_POST['deletepart'])) {
        $value_to_delete = $_POST['del'];
        $value_to_delete = $key;

        unset($_SESSION['arr'][$key]);
        $_SESSION["arr"] = array_values($_SESSION["arr"]);
    }

?>

非常感谢任何关于我在哪里出错的帮助!

【问题讨论】:

  • $key 数据从哪里来?
  • 您正在覆盖$value_to_delete=$key$value_to_delete 的值,将其替换为$key = $value_to_delete
  • @AbdullahRazzaki ...做到了!谢谢

标签: php session post


【解决方案1】:

试试这个

$key = $value_to_delete;而不是$value_to_delete = $key

<?php 

    if (isset($_POST['deletepart'])) {
        $value_to_delete = $_POST['del'];
        //$value_to_delete = $key; //instead of this use
         $key = $value_to_delete;

        unset($_SESSION['arr'][$key]);
        $_SESSION["arr"] = array_values($_SESSION["arr"]);
    }

?>

【讨论】:

  • 或使用unset($_SESSION['arr'][$_POST['del']]);
猜你喜欢
  • 2019-05-29
  • 2022-11-27
  • 1970-01-01
  • 2016-04-11
  • 1970-01-01
  • 2017-06-03
  • 2020-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多