duanne9313 2014-10-19 06:59
浏览 46
已采纳

将PHP数组名称转换为字符串的最佳方法

I have an HTML table, linked to PHP $_SESSION data, to which I wish to add a Delete button to every row that deletes not only that row from the HTML table, but also from the $_SESSION variable.

This is the code that populates my table:

tableData.php

// echo the table headings
echo <<<HERE
<tr>
    <th>CityID</th>
    <th>State</th>
    <th>City</th>
    <th></th>
</tr>
HERE;

if (isset($_SESSION['cityData']))
{

    foreach($_SESSION['cityData'] as $city)
    {
        echo "<tr>";
        // print each row of data
        foreach($city as $data)
        {
            echo "<td>" . $data . "</td>";
        }
        //echo '<td><button action="<?php unset(' . $_SESSION['cityData'][key($_SESSION['cityData'])] . ')?>">Delete Row</button></td>';
        echo "</tr>";
    }

}

The line that I commented out, echo '<td><button action="<?php unset(' . $_SESSION['cityData'][key($_SESSION['cityData'])] . ')?>">Delete Row</button></td>'; is the line that creates the button that I am trying to create, to do what I am wanting it to do. I am trying to figure out the best way to name the array that I want gone.

P.S. I know, I should have it invoke some other function that does both tasks, it is just, if I pass the array in like I did, it will complain of " Array to string conversion ". Is there a way to do what I am trying to do, cleanly?

  • 写回答

2条回答 默认 最新

  • douqilin4296 2014-10-19 07:14
    关注

    It's just not that simple. You need to get your buttons to submit to a link, and then have the PHP unset the content.

    foreach($_SESSION['cityData'] as $index => $city) //added $index =>
    {
        echo "<tr>";
        // print each row of data
        foreach($city as $data)
        {
            echo "<td>" . $data . "</td>";
        }
        echo '<td><form method="post" action=""><input type="hidden" name="delete" value="' . $index . '"><input type="submit" value="Delete Row"></form></td>';
        echo "</tr>";
    }
    

    So I added a form that a button that will submit to data that indicates the row number, so when your client clicks on the button, it will submit them and the row number will be passed as a POST variable.

    At the top of tableData.php, you can then have logic handling the delete. Simply check if the delete is set, and then attempt to unset from there.

    if (isset($_POST['delete']))
        unset($_SESSION['cityData'][$_POST['delete']]);
    

    You will want to have further validation that checks if POST delete within the bounds of $_SESSION['cityData'], but the basic idea is there.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)