2016-06-28 26 views
0

我有這樣的一個屏幕: notifications example無法從陣列中刪除數據行。 PHP + Javascript

它會刪除行,但只從屏幕上。因爲如果我刷新,它會再次出現。我不知道如何從實際數組中刪除它。 數組從csv文件中取出 - 我知道如何將其添加回來等。但我不知道從數組中刪除行。

繼承人我有:

// Grabs the csv file (and its existing data) and makes it into an array so the new data can be added to it. 
$Notifications = array(); 
$lines = file('data/AdminNotifications.csv', FILE_IGNORE_NEW_LINES); 
foreach ($lines as $key => $value) 
{ 
    $Notifications[$key] = str_getcsv($value); 
} 

echo array2table(array_reverse($Notifications)); 


// FUNCTION --------------------------------------------------------------------- 

//This converts an array to a table 
function array2table($array, $recursive = false, $null = ' ') 
{ 
    // Sanity check 
    if (empty($array) || !is_array($array)) { 
     return false; 
    } 

    if (!isset($array[0]) || !is_array($array[0])) { 
     $array = array($array); 
    } 

    // Start the table 
    $table = "<table>\n"; 

    // The header 
    $table .= "\t<tr>"; 

    // Take the keys from the first row as the headings 
    foreach (array_keys($array[0]) as $heading) { 

    } 

    $table .= "</tr>\n"; 

    // The body 
    foreach ($array as $row) { 
     $table .= "\t<tr>" ; 

     foreach ($row as $cell) { 
      $table .= '<td>'; 

      /* 
      if($cell ==0 && $heading==1){ 
      $cell = $cell.": "; 
     } 
      */ 

      $details = $cell; 


      // Cast objects 
      if (is_object($cell)) { $cell = (array) $cell; } 

      if ($recursive === true && is_array($cell) && !empty($cell)) { 
       // Recursive mode 
       $table .= "\n" . array2table($cell, true, true) . "\n"; 
      } else { 
       $table .= (strlen($cell) > 0) ? 
        htmlspecialchars((string) $cell) : 
        $null; 
      } 

$table .= '</td>'; 


     } 
      $table .= '<td>'; 


      $table .= '<input type="submit" value="Delete" onclick="deleteRow(this)" name="delete"/>'; 


      $table .= '</td>'; 



     $table .= "</tr>\n"; 
    } 

    $table .= '</table>'; 
    return $table; 
} 


//If the delete button is pressed, then it does this. 
if (isset($_POST['delete'])) { 

} 

?> 

//What happens when it is pressed. (This is javascript) 
<script> 
function deleteRow(btn) { 
    var row = btn.parentNode.parentNode; 
    row.parentNode.removeChild(row); 

} 

</script> 

任何幫助將不勝感激。我不太確定我是否可以使用javascript刪除一行?或者在php和java中...

謝謝

回答

0

作爲服務器端語言的PHP將只在服務器上執行。當你在這裏按下delete按鈕時,會調用一個javascript函數,它實際上是從客戶端刪除你的行,因爲它是客戶端語言,這意味着它實際上存在於該文件的服務器上,這就是爲什麼當你刷新它時再次顯示。

現在您可以創建一個ajax調用或者刪除表單中的按鈕來將該請求發佈到服務器以實際刪除該請求。

//If the delete button is pressed, then it does this. 
if (isset($_POST['delete'])) { 
    $arr_index = $_POST['delete']; //you need to pass the row number 
    unset($array[$arr_index]); 
} 
+0

感謝您的回覆。我明白你的意思是關於PHP作爲服務器端等 - 我想我寫了,因爲我正在嘗試幾件事情..但在目前的代碼,它沒有采取這種形式的價值,所以它不會做任何事情。抱歉。 當我嘗試了一些東西,我做了每個行都有一個刪除按鈕

與價值'刪除'的提交按鈕。 –

+0

我認爲這是類似於

+0

不需要對不起,我問,因爲我想知道你是否想在表單中使用刪除按鈕。那麼你是在一個正確的道路:)然後,如果你可以使用刪除語句,我會告訴你一段時間,但首先我需要知道你有任何id /行沒有列? –