1

データベース内の情報を JSON ファイルに読み込む作業を行っています。私が持っているコードはファイルを正常に読み取りますが、探しているのは、ファイルにまだ存在しない新しいデータのみを追加する方法です。コードを実行するたびに、データベースに保存されているすべての情報が毎回追加されます。

$con = mysql_connect('localhost', '', '') or die('Error connecting to server');

mysql_select_db('twitter', $con); 

$file = 'file.json';

$query = mysql_query('SELECT * FROM sample_data');

//Define columns 
$table = array();
$table['cols'] = array(
    array('label' => 'Username', 'type' => 'string'),
    array('label' => 'Retweet_count', 'type' => 'number'),
    array('label' => 'Origin', 'type' => 'string'),
    array('label' => 'Destination', 'type' => 'string'),
    array('label' => 'Text', 'type' => 'string'),
    array('label' => 'Sentiment_type', 'type' => 'string'),
    array('label' => 'Sentiment_score', 'type' => 'number'),
    array('label' => 'Profile_picture', 'type' => 'string'),
    array('label' => 'TweetID', 'type' => 'number')
);

$rows = array();
while($r = mysql_fetch_assoc($query)) {
    $temp = array();
    // each column needs to have data inserted via the $temp array
    $temp[] = array('v' => $r['Username']);
    $temp[] = array('v' => (int) $r['Retweet_count']); // typecast all numbers to the appropriate type (int or float) as needed - otherwise they are input as strings
    $temp[] = array('v' => $r['Origin']);
    $temp[] = array('v' => $r['Destination']);
    $temp[] = array('v' => $r['Text']);
    $temp[] = array('v' => $r['Sentiment_type']);
    $temp[] = array('v' => (double) $r['Sentiment_score']);
    $temp[] = array('v' => $r['Profile_picture']);
    $temp[] = array('v' => (int) $r['TweetID']);

    // insert the temp array into $rows
    $rows[] = array('c' => $temp);
}

// populate the table with rows of data
$table['rows'] = $rows;

file_put_contents($file, json_encode($table, JSON_FORCE_OBJECT), FILE_APPEND | LOCK_EX);

// Read it back out with
echo file_get_contents($file);


// set up header; first two prevent IE from caching queries
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

ご協力ありがとうございました!

4

1 に答える 1

0

新しいデータをjson文字列に「追加」することはできません。通常、構文エラーが発生してjsonが破壊されます。JSON 文字列は構文的に有効な JavaScript でなければならないことに注意してください。

したがって、json文字列が次のように始まる場合

['a','b','c'];

そして、いくつかの新しい配列要素を追加すると、最終的には次のようになります

['a','b','c']['d',e'];

それは有効なjson / javascriptではないため、ガベージを取得します。

json をデコードしてネイティブ PHP 構造に戻し、そこに追加してから、json に再エンコードする必要があります。

$json = '....';
$array = json_decode($json);

while( ... ) {
  $array[] = $new_data;
}
$json = json_encode($array);
于 2013-07-17T18:44:06.230 に答える