我正在努力将数据库中的信息读入 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');
感谢您的帮助!
最佳答案
您不能只是将新数据“附加”到 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);
关于php - 使用 PHP 将新的 MySQL 数据附加到 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17707686/