如何删除特定的数组?

时间:2016-03-24 19:25:26

标签: php mysqli

好的dokie。让我们看看我是否可以正确解释自己。在我的数据库的两个单独的行中,我有如下所示的数据:

row1 (labeled "claimed") = Item1, Item2, Item3, Item4
row2 (labeled ctype) = Thing1, Thing2, Thing3, Thing4

我已经提取了数据,所以他们就这样组合在一起:

Item1, Thing1
Item2, Thing2...

使用此代码:

<?php
$select=mysqli_query($connect, "SELECT * FROM `$table_members` WHERE email='$_SESSION[USR_LOGIN]'");
while($row1=mysqli_fetch_assoc($select)) {
    $name1=$row1['name'];
    $claim = $row1['claimed'];
    $type1 = $row1['ctype'];
    if ($claim != 'None') {
        $type2 = explode(', ', $type1);
        $decks = explode(', ', $claim);
        echo "<table id=\"memtable\"><tr><th>Name</th><th>Claimed</th><th>Type</th></tr>";
        foreach(array_combine($decks, $type2) as $deck => $type3){
            echo "<tr><td>";
            echo "$name1</td><td>";
            echo "$deck</td><td>";
            echo "$type3</td><td>";
        }
    }
} 
?>

现在的问题是,在成员提交表单后,我想根据他们的提交从数据库中删除项目和事物。例如,我有一个下拉列表

-Item1
-Item2...

他们选择Item2并提交表格。现在我只想从我的数据库中删除Item2和Thing2,所以现在这些行看起来像这样:

row1 (labeled "claimed") = Item1, Item3, Item4
row2 (labeled ctype) = Thing1, Thing3, Thing4

我似乎无法弄清楚如何对其进行编码,以便只删除一个特定实例。 我假设它类似于以下内容:

foreach(array_combine($decks, $type2) as $deck => $type3){
$gone = "DELETE FROM `$table_members` WHERE claimed='$deck' AND ctype='$type3'";
            mysqli_query($connect, $gone);
}

ETA:我找到了解决方案!对于任何寻找相同类型的东西的人来说,这就是我所做的:

$remove = $_POST['remove;']

$select1=mysqli_query($connect, "SELECT * FROM `$table_members` WHERE email='$_SESSION[USR_LOGIN]'");
while($row1=mysqli_fetch_assoc($select1)) {
    $claim = $row1['claimed'];
    $type1 = $row1['ctype'];
}
$type2 = explode(', ', $type1);
$decks = explode(', ', $claim);
for($i=0;$i<count($decks);$i++){
    if($decks[$i]===$remove){unset($decks[$i]); unset($type2[$i]);}
}
$decks = implode(', ',$decks);
$type2 = implode(', ',$type2);
$gone = "UPDATE `$table_members` set claimed='$decks', ctype='$type2' where email='$_SESSION[USR_LOGIN]'";
     mysqli_query($connect, $gone);

1 个答案:

答案 0 :(得分:0)

让我们看看我的情况是否正确。

表格中的数据如下所示:

 -------------------------------------------------------------------------
|  Name   |  ctype                          |  claimed                    |
--------------------------------------------------------------------------
|  Jhon   | Thing1, Thing2, Thing3, Thing4  |  Item1, Item2, Item3, Item4 |
 -------------------------------------------------------------------------

在这种情况下,如果您只想删除一个项目,我认为您最好的选择是:

$email = $_SESSION['USR_LOGIN'];
foreach(array_combine($decks, $type2) as $deck => $type3)
{
     $gone = "UPDATE `$table_members` set claimed=REPLACE(claimed,'$deck, ',''), ctype=REPLACE(ctype,'$type3, ', '') where email='$email'";
     mysqli_query($connect, $gone);
}

如果您可以在表格中发布数据组织方式的示例,我想我可以提供更好的示例。