2015-11-07 55 views
-1

我有一个视频ID数组,当用户单击某个按钮时,点击的视频的videoId会附加到该数组。PHP-JSON在取消设置值时保存为错误格式

当用户再次点击同一按钮时,代码搜索videoId,如果找到,则从阵列中删除视频ID。

数组保存在一个JSON文件,其格式为["aaa","bob"...]然而,当我从阵列中删除一个值的JSON文件转化为{"1":"aaa", "2":"bbb"...}

我怎样才能防止这种情况发生?

PHP:

$NameFileJSON = $_GET["NameFile"]; 
$VideoId = $_GET["VideoId"]; 
$removeVideoId = $_GET["RemoveVideoId"]; 

$results = array($VideoId); 

SAVE VIDEOID:

if (($NameFileJSON != "")&&($VideoId != "")&&($removeVideoId == "")){ 

     $filename = "json/likesJSON/$NameFileJSON.json"; 

     if (file_exists($filename)) { 

      echo "The file $filename exist"; 

      $inp = file_get_contents("json/likesJSON/$NameFileJSON.json"); 
      $arr = json_decode($inp); 

      array_push($arr, $results[0]); 

      $fp_login = fopen("json/$NameFileJSON.json", w); 
      fwrite($fp_login, json_encode($arr)); 
      fclose($fp_login); 

     } else { 

      echo "The file $filename does not exist"; 
      $fp_login = fopen("json/$NameFileJSON.json", w); 
      fwrite($fp_login, json_encode($results)); 
      fclose($fp_login); 

     } 

}

DELETE VIDEOID:

if (($NameFileJSON != "")&&($VideoId == "")&&($removeVideoId != "")){ 

    $inp = file_get_contents("json/$NameFileJSON.json"); 
      $arr = json_decode($inp); 

    if (($index = array_search($removeVideoId, $arr)) !== false) { 
     echo $index; 
     unset($arr[$index]); 
    } 

      $fp_login = fopen("json/$NameFileJSON.json", w); 
      fwrite($fp_login, json_encode($arr)); 
      fclose($fp_login);  

} 

print_r(json_encode($arr) 
+0

你尝试'方法Array.splice()'在JavaScript中,而不是'delete'?或者,删除是什么意思? – PHPglue

+0

它是php方面的行为。 'array_values'可以在这里帮助.. –

回答

0

相同@Barry说,如果你仍然想保存为JSON数组,你可以使用这个

if (($NameFileJSON != "")&&($VideoId == "")&&($removeVideoId != "")){ 

    $inp = file_get_contents("json/$NameFileJSON.json"); 
      $arr = json_decode($inp); 

    if (($index = array_search($removeVideoId, $arr)) !== false) { 
     echo $index; 
     unset($arr[$index]); 
    } 
    $arr = array_values($arr); 

      $fp_login = fopen("json/$NameFileJSON.json", w); 
      fwrite($fp_login, json_encode($arr)); 
      fclose($fp_login);  

} 

print_r(json_encode($arr) 

多见于http://php.net/manual/en/function.array-values.php

0

json_encode只会产生数组符号后,如果数组索引从0开始sequental号码。当您使用unset()时,它会在索引中创建一个间隙,所以它会作为对象发送以维护索引。出于这个原因,unset()通常应该只用于关联数组。

使用array_splice()而不是unset()从数组中删除一个元素,然后将它下移后的所有索引。

array_splice($arr, $index, 1); 
0
  1. 您可以array_splice取代你unset
    array_splice($array, $i, 1);
  2. 您可以重置索引array_values
    json_encode(array_values($array));