1

我正在codeigniter中编写一个删除函数。用户有两种选择。全部删除或删除一行。我不想重复相同的代码,我使用这样的功能。但是有一个错误“解析错误:语法错误,意外的 T_ELSE”。我该如何解决这个问题?重复代码的唯一方法?

public function _delete_port()
{
    if ($_GET['delete_all']): 
        foreach ($_GET['delete_id'] as $delete_id):         
    else:
        $delete_id = $_GET['delete_id'];
    endif;
        // Some controls
        // ...

        $this->db->delete('ma_port', array('id' => $delete_id));

    if ($_GET['delete_all']) :
        endforeach;
    endif;

    redirect($url);
}
4

2 回答 2

1

您的代码面临的主要问题似乎是对流控制如何工作的误解。您采用的方法是尝试使用if / else / endif来构造您希望代码的外观,而不是您希望代码执行的操作

$_GET['delete_all']如果作为数组存在,您的过程是使用循环,否则使用$_GET['delete_id']. 所以首先检查变量的内容,然后采取适当的措施。如果不存在,则可以通过放入$_GET['delete_id']数组来简化整个事情。$_GET['delete_all']

// Empty array we'll fill later
$delete_ids = array();

// If the delete_all array is available, use it as the array to delete from
if (isset($_GET['delete_all']) && is_array($_GET['delete_all'])) {
  $delete_ids = $_GET['delete_all'];
}
// Next if delete_id is present
else if (isset($_GET['delete_id'])) {
  // Place it into the array to use later
  $delete_ids[] = $_GET['delete_id'];
}
else {
  // Neither was set, you have an error state, so handle it however you need to
  // Redirect, display an error, whatever.
}

// Now loop over your array and perform the action.
// The array either contains the original array from $_GET['delete_all'] or the single element $_GET['delete_id']
// Or it may be empty entirely, and therefore won't do anything
foreach ($delete_ids as $delete_id) {
  $this->db_delete('ma_port', array('id' => $delete_id));
}

// And finish with your redirect
redirect($url);
于 2013-10-25T13:26:21.780 回答
0

那太脏了,我应该是一个更好的翻译:

public function _delete_port()
{
    if ($_GET['delete_all']): 
        foreach ($_GET['delete_id'] as $delete_id):         
            // Some controls
            // ...
            $this->db->delete('ma_port', array('id' => $delete_id));
        endforeach;
    else:
        $delete_id = $_GET['delete_id'];
        $this->db->delete('ma_port', array('id' => $delete_id));
    endif;
    redirect($url);
}
于 2013-10-25T13:24:01.960 回答