2016-08-03 4 views
0

私はプログラムで作業していますが、複数のエントリを許可する余分な書き込みコマンドを投げる場所を特定できません。私の最終的な配列は、それは新しい投稿が来たときにそれがreimportedすることができます。任意のアイデア? check.jsonファイルにエントリが1つだけを保っている...PHPのインポートされたjsonファイルに複数行のエントリが必要です

<?php 
#$myFile = file("check.json", FILE_IGNORE_NEW_LINES);  
$myFile = "check.json"; 
#$arr_data = array(); // create empty array 
$code = $_POST['code']; 
    try 
    { 
     //Get form data 
     $formdata = array(
      $code=> $_POST['cpu'], 
     ); 
     //Get data from existing json file 
     $jsondata = file_get_contents($myFile, FILE_IGNORE_NEW_LINES); 
     // converts json data into array 
     $arr_data = json_decode($jsondata, true);  
     // loops through the formdata array 
     foreach ($formdata as $f) { 
     #if data is in there then replace 
      if(in_array($f, $arr_data)) { 
       echo "$f is found..."; 
       foreach ($arr_data as $a) { 
        if (strpos($a, $f) !== false) { 
         echo "$a is checking in...", "<br>"; 
         // Push user data to array 

        } 
        else 
         echo "Formdata is subtracted by 1...", "<br>"; 
         // Push user data to array, minus 1 from value 
       } 
      } 
      else 
       echo "$f is Not in the array..."."<br>"; 
       // Push user data to array 
       array_push($arr_data,$formdata); 
       //Convert updated array to JSON 
       $jsondata = json_encode($formdata);    
       //write json data into data.json file 
       if(file_put_contents($myFile, $jsondata)) { 
        echo 'Data successfully saved'; 
       } 
       else 
        echo "error"; 
     }  
    } 
    catch (Exception $e) { 
      echo 'Caught exception: ', $e->getMessage(), "\n"; 
    } 
?> 

t9.html

<form action="test9.php" method="POST"> 
CPU Name:<br> 
<input type="text" name="cpu"> 
<br><br/> 
Code:<br> 
<input type="text" name="code"> 
<br><br> 
<input type="submit" value="Submit"> 
</form> 

check.json { "10": "トミー"}

答えて

0

たびにfile_put_contents()ファイル全体を書き直しています。内容を消去して現在の内容を書き出します。$jsondataあなたがしたいことは、そのファイルを$jsondataに読み込み、$jsondataを新しい値で修正してから書き換えますそれはまた戻ってくる。

関連する問題