2015-05-07 28 views
1
$files = array("post", "name", "date"); 

$post = $_POST["comment"]; 
$name = $_POST["name"]; 
$date = date("H:i F j"); 

foreach ($files as $x) { 
    $file = fopen("db/$x.txt", "a"); 
    $x = "$" . $x; 
    fwrite($file, $x); 
    fclose($file); 
} 

試圖分別放$post, $name$date值到post.txt,name.txt和date.txt文件,但是卻讓文字"$post"到post.txt等等。請幫忙!如何變量保存到一個文件

+0

只是一個想法:你可能想看看DB-Systems,爲你正在做什麼。例如。 sqlight可以幫助你存儲你的東西。 – kratenko

+0

聯合數組可行,但sgtBOSE的方法更有效一些。但無論如何感謝所有幫助過的人! – PyRoss

回答

1

嘗試用variable of variable -

foreach ($files as $x) { 
    $file = fopen("db/$x.txt", "a"); 
    $x = $$x; 
    fwrite($file, $x); 
    fclose($file); 
} 

變量變量取變量的值並設爲,作爲一個變量的名稱。

你會得到的細節here

1

使用數組代替它是正確的選擇。

$values = array(
    'comment' => $_POST["comment"], 
    'name' => $_POST["name"], 
    'date' => date("H:i F j") 
); 

foreach ($values as $x) { 
    $file = fopen("db/$x.txt", "a"); 
    fwrite($file, $x); 
    fclose($file); 
} 
1

您使用$ X = 「$」。$ X不給你你想要的值。 試試這個:

$files = [ 
    'comment' => $_POST['comment'], 
    'name' => $_POST['name'], 
    'date' => date('H:i F j') 
]; 

foreach($files as $name => $value) { 
    $file = fopen("db/$name.txt", "a"); 
    fwrite($file,$value); 
} 
相關問題