2016-03-26 21 views
2

JSON dizisinden bir öğeyi silmeye çalışıyorum. Eylem, kullanıcı bir silme düğmesine tıkladığında başlar. Neyin yanlış olduğunu anlayamıyorum. Belki PHP betiğinde bir şeydir.JSON dizisinden öğe sil

javascript.js

$(".delete").on('click', function(e){ 
     var deleteItem = e.target.id; 
     console.log(deleteItem); 
     $(this).closest('div').css({"text-decoration": "line-through", "color": "#e74c3c"}).fadeOut(600); 
     $.ajax({ 
      url: 'deletejson.php', 
      method: 'POST', 
      dataType: 'json', 
      data: { target: e.target.id}, 
      success: function(){ 
       console.log('Item was deleted'); 
       console.log(data); 
      } 
     });  

Data.JSON

{ "prescriptions":[ 
    { 
    "name":"Edogen", 
    "unit":"drops", 
    "dosage":"2 drops", 
    "doc_name":"Dr. Wu", 
    "apperance":"black", 
    "days":"Monday", 
    "frequency":"twice", 
    "hour":"1pm" 
    }, 
    { 
    "name":"Lexapro", 
    "unit":"drops", 
    "dosage":"2 drops", 
    "doc_name":"Dr. Wu", 
    "apperance":"black", 
    "days":"Sunday", 
    "frequency":"twice", 
    "hour":"1pm" 
    }, 
    { 
    "name":"Plavix", 
    "unit":"drops", 
    "dosage":"4 drops", 
    "doc_name":"Dr. Ammy Lee", 
    "apperance":"blue", 
    "days":"Monday", 
    "frequency":"twice", 
    "hour":"10pm" 
     } 
    ]} 

<?php 

$var = $_POST["target"]; 
$file = "json/data.json"; 

$json_array = json_decode(file_get_contents($file), true); 


function removeNode($var, $json_array) { 
    foreach($json_array["prescriptions"] as $key => $value) { 
     if($value === $var) 
     unset($json_array["prescriptions"][$key]);   
    } 

    $json = json_encode($json);  
    file_put_contents($file, $json); 
} 

?> 
+0

ajax çağrısı ile veriyi değişken olarak alıyor musunuz? – NomanJaved

+0

Php günlükleri ne diyor? Javascript konsolu herhangi bir hata veriyor mu? – Torchify

+0

Evet. Kodun başka bir bölümünde verileri çağırıyorum. – tcosta

cevap

0

ile foreach döngüsü değiştirmeyi deneyin deletejson.php aşağıdaki:

foreach($json_array["prescriptions"] as $values) { 
    foreach($values as $key => $value) { 
    if($value === $var){ 
     unset($json_array["prescriptions"][$key]); 
    } 
    }   
}