如何从按钮php获取数组索引

时间:2021-12-29 09:02:23

i have an array with objects that i have submitted to display in the form with foreach, i did it like that:

我有一个数组与我提交的对象显示在foreach表单中,我这样做:

<?php session_start(); if(isset($_SESSION['objectList'])){
foreach($_SESSION['objectList'] as $object){
    ?>
     <form action="control.php" method="post">
    <input type="submit" name="op" value="-" /> <?php echo $object;?>
    </form>
<?php } 
}else{
echo "No hay objetos";
}
?>

When the "-" button is pressed, the position of the array of that button must be eliminated, that is done with the following code in another class:

按下“ - ”按钮时,必须消除该按钮数组的位置,这是通过另一个类中的以下代码完成的:

unset($_SESSION['objectList'][$object]);
$_SESSION['objectList']=array_values($_SESSION['objectList']);

But I do not know how to send the index value of the pressed button

但我不知道如何发送按下按钮的索引值

It looks like this empty array 3 object in the array

它看起来像数组中的这个空数组3对象

1 个解决方案

#1


2  

you can add the index as a hidden input like this:

您可以将索引添加为隐藏输入,如下所示:

<?php session_start(); if(isset($_SESSION['objectList'])){
foreach($_SESSION['objectList'] as $index => $object){
    ?>
     <form action="control.php" method="post">
     <input type="hidden" name="index" value="<?= $index; ?>" />
    <input type="submit" name="op" value="-" /> <?php echo $object;?>
    </form>
<?php } 
}else{
echo "No hay objetos";
}
?>

the index is then in the $_POST variable $_POST['index']

然后索引在$ _POST变量$ _POST ['index']中

But be carefull if you use a numeric index, because if you unset it, then the indexes might not be correct anymore. Better use a associative array.

但是如果你使用数字索引要小心,因为如果你取消它,那么索引可能不再正确。更好地使用关联数组。

#1


2  

you can add the index as a hidden input like this:

您可以将索引添加为隐藏输入,如下所示:

<?php session_start(); if(isset($_SESSION['objectList'])){
foreach($_SESSION['objectList'] as $index => $object){
    ?>
     <form action="control.php" method="post">
     <input type="hidden" name="index" value="<?= $index; ?>" />
    <input type="submit" name="op" value="-" /> <?php echo $object;?>
    </form>
<?php } 
}else{
echo "No hay objetos";
}
?>

the index is then in the $_POST variable $_POST['index']

然后索引在$ _POST变量$ _POST ['index']中

But be carefull if you use a numeric index, because if you unset it, then the indexes might not be correct anymore. Better use a associative array.

但是如果你使用数字索引要小心,因为如果你取消它,那么索引可能不再正确。更好地使用关联数组。