我有以下代码。有什么方法可以结合并简化它吗?For和While循环在php mysql中
json.html文件中的输出应如下所示:["abc","def","ghi"]
。
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "admin") or die(mysql_error());
mysql_select_db("test1") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM test_auto_complete") or die(mysql_error());
$menu = array();
while($row = mysql_fetch_assoc($result))
{
$menu[] = array("id" => $row['username'],);
}
foreach($menu as $key=>$value)
{
$menu[$key] = $value['id'];
}
$my_json_content = json_encode($menu);
$file = 'json.html';
$current = file_get_contents($file);
file_put_contents($file, $my_json_content);
?>
我知道代码看起来很糟糕,但即便如此,有人可以帮助我吗?
谢谢
阿里汉
请勿使用mysql_ *将它们更改为PDO或mysqli原因mysql_ *是depracated。看来你不使用$ current变量,所以你为什么得到文件的内容?你想使用foreach,我没有得到它 – Robert 2013-05-10 10:20:16