Javascript 如何使用explode函数分隔和显示不同的值

Javascript 如何使用explode函数分隔和显示不同的值,javascript,php,arrays,explode,Javascript,Php,Arrays,Explode,我正在为我的英语课做一个随机句子生成器。我很接近,但由于我有限的php和javascript知识,我需要寻求帮助。我在阅读代码方面并不差,只是在写代码时遇到了麻烦 我想使用explode来分解逗号分隔的值字符串。字符串是英语和西班牙语的混合体,在.txt文件中,它们将分开,如下所示: The book, El libro The man, El hombre The woman, La mujer 等等 我想将这两个值分成一个数组,并在我的网页上的不同位置显示它们。 我将使用我发现的一个随机文

我正在为我的英语课做一个随机句子生成器。我很接近,但由于我有限的php和javascript知识,我需要寻求帮助。我在阅读代码方面并不差,只是在写代码时遇到了麻烦

我想使用explode来分解逗号分隔的值字符串。字符串是英语和西班牙语的混合体,在.txt文件中,它们将分开,如下所示:

The book, El libro
The man, El hombre
The woman, La mujer
等等

我想将这两个值分成一个数组,并在我的网页上的不同位置显示它们。 我将使用我发现的一个随机文本生成器脚本,它工作得很好,没有问题。我只需要使用explode来修改它,将值分离到一个数组中,并能够显示数组的单独值

<?php

/* File, where the random text/quotes are stored one per line */
$settings['text_from_file'] = 'quotes.txt';

/*
How to display the text?
0 = raw mode: print the text as it is, when using RanTex as an include
1 = Javascript mode: when using Javascript to display the quote
*/
$settings['display_type'] = 1;

/* Allow on-the-fly settings override? 0 = NO, 1 = YES */
$settings['allow_otf'] = 1;

// Override type?
if ($settings['allow_otf'] && isset($_GET['type']))
{
$type = intval($_GET['type']);
}
else
{
$type = $settings['display_type'];
}

 // Get a list of all text options
if ($settings['text_from_file'])
{
$settings['quotes'] = file($settings['text_from_file']);
}

// If we have any text choose a random one, otherwise show 'No text to                              choose from'
if (count($settings['quotes']))
{
$txt = $settings['quotes'][array_rand($settings['quotes'])];
}
else
{
$txt = 'No text to choose from';
 }

// Output the image according to the selected type
if ($type)
{
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);

// Set the correct MIME type
header("Content-type: text/javascript");

// Print the Javascript code
echo 'document.write(\''.addslashes($txt).'\')';
}
else
{
echo $txt;
}
?>
显示结果的脚本:

 <script type="text/javascript" src="rantex.php?type=1"></script>
有人能帮我修改rantex.php文件,这样我就可以使用explode来分隔不同的逗号分隔值,并使用不同的脚本在我的网页上的不同位置调用它们吗


谢谢您,请原谅我的不详。

以下内容似乎没有必要,因为文件将已删除新行字符:

// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);

似乎您正试图使用PHP为带有一些随机句子的静态页面提供服务,对吗?那么为什么不使用PHP来提供有效的JSON,并在客户端上显示逻辑呢

下面是一个快速实现

// Get the data from the text file
$source = file_get_contents('./quotes.txt', true);

// Build an array (break on every line break)                           
$sentences = explode("\n", $source);

// Filter out empty values (if there is any)
$filtered = array_filter($sentences, function($item) { 
  return $item !== "";
});

// Build a hashmap of the array
$pairs = array_map(function($item) { 
  return ['sentence' => $item];
}, $filtered);

// Encode the hashmap to JSON, and return this to the client.
$json = json_encode($pairs);
现在,您可以使用一些基本的JavaScript让客户端处理其余部分

// Return a random sentence from your list.
var random = sentences[Math.floor(Math.random() * sentences.length)];

// Finally display it
random.sentence
[编辑]

您可以通过多种方式将JSON数据发送到客户端,但如果您不想使用Ajax之类的工具,只需将内容转储到网页上,然后使用JavaScript从全局窗口对象更新随机语句即可

// Inside your php page

<p>English: <span id="english"></span></p>
<p>Spanish: <span id="spanish"></span></p>

<script>

  var sentences = <?= json_encode($pairs); ?>;
  var random = sentences[Math.floor(Math.random() * sentences.length)];

  var elspa = document.getElementById('spanish');
  var eleng = document.getElementById('english');

  elspa.innerText = random.sentence.split(',')[1];
  eleng.innerText = random.sentence.split(',')[0];

</script>

好的,我已经弄明白了,我拿了0分,因为我付钱给了别人。特别感谢@stormpat让我走上了正确的方向,如果不是他,我就不会从JSON的角度来看这个问题

.PHP文件如下所示:

<?php
$f_contents = file('quotes.txt'); 
$line = trim($f_contents[rand(0, count($f_contents) - 1)]);
$data = explode(',', $line);
$data['eng'] = $data[0];
$data['esp'] = $data[1];

echo json_encode($data);
?>
在标题的.HTML页面上:

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>
    (function ($) {
        $(function()
        {
            function load_random_data() {
                $.get('random_line.php', function(data) {
                    var data = $.parseJSON(data);
                    $('#random_english').text(data.eng);
                    $('#random_spanish').text(data.esp);
                });
            }
            load_random_data();
            $('#get_random').click(function(e){
                e.preventDefault();
                load_random_data();
            });


        });
    })(jQuery);
    </script>
这会将不同的变量拆分为类,因此要将它们调用到我的html页面中,我会按它们的类调用它们,例如,我想将变量放入一个表单元格中,所以我给了单个td单元格一个类:

                <td id="random_spanish"></td>
                <td id="random_english"></td>
另外,作为奖励,编码人员添加了一个漂亮的按钮来刷新json类:

<input type="button" value="Get random" id="get_random" />
所以现在我不必让我的学生刷新整个网页,他们只需点击按钮刷新随机变量即可


再次感谢大家

我希望我读的代码是正确的。如果将$txt值拆分为$english$spanish值,我如何用不同的Javascript将它们分开?我知道我可以使用股票,但不能在我的网页上的两个不同位置使用股票。感谢使用您的方法进行的翻转测试,我可以调用$english值,但不能调用$spanish值。我试着用这个:echo'document.write\.addslashes$english';echo'document.write\.addslashes$spanish.\;}else{echo$txt;}这有点不对,对吧?脚本假设每行之间都有一个逗号,后跟一个空格。不清楚通过调用两次脚本想要实现什么。如果您想在HTML中写入两个不同的位置,请尝试使用:echo'document.getElementById'id1'。innerHtml=\+addslashes$english+'\'是的,我后来看到了额外的空间,但我仍然被阻塞了。是的,不,我不想调用它两次,但我确实需要在.PHP上执行逻辑,并在静态HTML页面上使用JavaScript分别调用$english和$spanish变量。感谢您的帮助我使用的随机生成器确实使用PHP来处理逻辑,我可以在静态网页上使用JavaScript或PHP。我有兴趣尝试一下你建议的方法,尽管我不知道如何实施。我讨厌要求手持设备,但你能建议我如何在我的网页上调用这些值吗?感谢您的关注哦,很难不知道其余的设置,但基本上只是掌握.txt文件所在的路径,并使用上述方法解析文件。如果您使用的是香草PHP和HTML混合,那么您可以在页面中回显结果,并从窗口对象用JavaScript获取结果。如果您有某种MVC设置,您可以从控制器返回JSON,甚至可以通过AJAX调用获取JSON内容。当网站准备好了,我会得到适当的主机来处理我的需要,所以我会开放到最好的格式。你建议的方法似乎比我在网上找到的脚本要有效得多,我可以阅读它并看到它的发展方向,但我不确定我网页上的JavaScript会是什么样子。它当前用于一个值。谢谢。编辑了我的答案。我希望它会有帮助。是的,它很有帮助。谢谢。我认为这是一个误会,这是我的错,没有看到它更快。是的,我确实想去 生成随机的句子,但我需要更多的控制。当我生成一些随机单词时,我需要将它们的西班牙语含义连接起来,以便在英语单词下显示。计划是有一个文本文件,其中包含两个值的列表,用逗号分隔:书籍、El libro等。随机性是获得给定的随机行所必需的,但我需要在逗号处解析它们,因此我有一个英语值和一个西班牙语值,可以分别显示。再次感谢
<input type="button" value="Get random" id="get_random" />