unset()没有按预期工作

时间:2016-06-27 01:24:12

标签: php json

以下是我删除JSON数组中对象的代码。

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);

}

应该这样做: 在调用函数JSON数组值之前:

{"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"}]}

它应删除' english_courses'内的任何对象。课程数组,但不是删除它这样做:

{"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"}}}

这是obj_val代码:

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 { } } 

这就是'#op'设置:

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); } 

基本下拉列表由动态数据填充。当一个值被选中时,它会进入一个php文件,根据obj_val的值删除一个json数组的特定obj

只有当obj_val为&#39; 0&#39;和php函数必须删除数组的第一个索引。否则它可以正常工作

请帮助!!

1 个答案:

答案 0 :(得分:3)

你必须重新索引$ data数组,问题是当你尝试取消设置($ data ....)所以第一个索引从&#34; 1&#34;它应该从&#34; 0&#34; ,那么它会正常工作

How to Remove Array Element and Then Re-Index Array?