lundi 27 juin 2016

unset() not working as expected

Following is my code to delete an object inside a JSON array.

if($_GET['method']=='deleteStudentReflections'){

        $jsonString = file_get_contents('../admin/data/student_reflection.json');

        $data = json_decode($jsonString, true);
        print_r($data["student_reflections"]); 
        unset($data["student_reflections"][$_GET['obj_val']]);

        $newJsonString = json_encode($data);

        file_put_contents('../admin/data/student_reflection.json', $newJsonString);

        print_r($_GET);

}

it should do this: Before calling function JSON array value:

{"english_courses":[{"name":"Abdullah","detail":"Bad Boy","image_link":"images/dp.jpg"},{"name":"Course Chin 2","detail":"Course det 2","image_link":"images/explicit feedly 3.PNG"},{"name":"courses 3 chinese","detail":"courses detail chinese 3","image_link":"images/site turorial.png"}]}

it should delete any object inside 'english_courses' courses array, but instead of deleting it does this:

{"english_courses":{"0":{"name":"Abdullah","detail":"Bad Boy","image_link":"images/dp.jpg"},"2":{"name":"courses 3 chinese","detail":"courses detail chinese 3","image_link":"images/site turorial.png"}}}

this is obj_val code:

function deleteEnglishCourse() { 
           var obj_val=$('#op').val(); 
           console.log(obj_val); 
           var deleteConfirm = confirm("Press 'Ok' to continue, Press 'Cancel' to Cancel "); 
          if (deleteConfirm == true) { 
             $.ajax ({ type: "GET", url: 'delete.php', data: "obj_val="+obj_val+"&method=deleteEnglishCourse", success: function(data) {alert(data); location.reload(); } }); } else { } } 

this is how '#op' is set:

function displayData(data){ 
            var html="<select id='op' class='form-control' onchange='valueSelect(this.value);'>"; for(var i=0;i<data["english_courses"].length;i++){ html+='<option value="'+i+'">' + data["english_courses"][i]["name"] + '</option>'; } 
   html+='</select>'; 
   $('#name_dropdown').append(html); } 

basically dropdown is populated by dynamic data. and when a value is selected it gets to a php file where a particular obj of a json array is deleted based on the value of obj_val

this error only occurs when obj_val is '0' and php function has to delete the first index of the array. Otherwise it works fine

please help !!

Aucun commentaire:

Enregistrer un commentaire