如何在 PHP 中制作最后一个数组编号 id +1 的 JavaScript 数组


How do I make a JavaScript Array in PHP going of the last array number id +1?

好吧,我一直在寻找这个有点技巧问题的答案。我有一个网站,通过使用JavaScript数组列表运行随机Google搜索。我有另一个网站与另一个网站一起使用,允许用户输入自己的搜索主题。这些用户输入的值进入一个巨大的文本文件,我喜欢称之为游乐场。

我想做的是让 PHP 脚本将用户输入的值写入 JavaScript 数组,但使用上次输入的 JavaScript 数组中的数组编号 id 加 1。

例:输入的最后一个数组是rand[60] = "hello";乔恩·多伊进入"test" .php 脚本写入topics.js fie,rand[61] = "test";

我已经有一个用于php的文件编写脚本...

<?php
//Idea Poster
$idea = $_POST['idea'];
//Idea DATA
$data = "$idea 'n'n ";
//Idea Writer
$fh = fopen("Ideas.txt", "a");
fwrite($fh, $data);
//Closer
fclose($fh);
//Reload Page
$page = "POSindex.php";
$sec = "0";
header("Refresh: $sec; $page");
?>

您可以保持编写脚本不变,然后编写脚本来读取.txt文件并将其即时转换为 JSON 数组。

假设你想形成一个有效的JS文件:

echo 'var topics = ', json_encode(file('Ideas.txt'));

优化

上面的脚本将始终读取文件并将内容编码为 JSON;这可以通过保留缓存文件来优化。

if (!file_exists('topics.json') || filemtime('topics.json') < filemtime('Ideas.txt')) {
    // changes were made to Ideas.txt
    $topics_js = 'var topics = ' . json_encode(file('Ideas.txt'));
    // update cache file
    file_put_contents('topics.json', $topics_js);
    echo $topics_js;
} else {
    // read from cached file
    readfile('topics.json');
}

请改用 JSON 数组。从文件中读取 JSON,对其进行解码,将元素添加到数组中,对其进行编码,然后将其写出。

首先以

json 格式存储数据即可。

<?php
//Idea Poster
$idea = $_POST['idea'];
//Idea DATA
$data = "$idea 'n'n ";
//Idea File (contains a json array)
$fh = fopen("Ideas.json", "r");
$contents = fread($fh, filesize("Ideas.json"));
fclose($fh);
// decode json
$ideas = json_decode($contents);
// add the new entry
$ideas[] = $idea;
// write it out 
$fh = fopen("Ideas.json", "w");
fwrite($fh, json_encode($ideas));
fclose($fh);
//Reload Page
$page = "POSindex.php";
$sec = "0";
header("Refresh: $sec; $page");
?>

或者,如果你真的需要该文件是单行纯文本,你可以使用 php 'file' 函数将其作为 php 数组读取,然后通过 'json_encode' 运行它以获得一个 json 数组。您可能需要对文件中的双倍间距做一些事情,但基本上您应该得到所需的内容。