我正在构建一个网站字典,您可以一次搜索多个单词。我有一个按钮来添加输入,每个术语一个。现在,我使用这些输入并通过字典网站(合法地)我获得他们的定义并将自己的CSS样式应用于他们。因此,当您在输入1中键入单词时(让我们称之为),您可以在输入旁边的div中定义它。所以我有一个变量来请求单词,另外四个用于获取和样式,最后一个“echo”用于输出。这是代码:
enter code <?php
$data = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/\1', $data);
$word = $_REQUEST['word'];
$word2 = $_REQUEST['word2'];
$url = "http://lema.rae.es/drae/srv/search?val={$word}";
$url2 = "http://lema.rae.es/drae/srv/search?val={$word2}";
$css = <<<EOT
<style type="text/css">
</style>
EOT;
$data = file_get_contents($url);
$data2 = file_get_contents($url2);
$data = str_replace('<head>', $css.'</head>', $data);
$data2 = str_replace('<head>', $css.'</head>', $data2);
$data = str_replace('<span class="f"><b>.</b></span>', '', $data);
$data2 = str_replace('<span class="f"><b>.</b></span>', '', $data2);
echo '<div id="result1"
style="">
'.$data.'
</div>';
echo '<div id="result1"
style="">
'.$data2.'
</div>';
?>
问题:如何为每个添加的新输入自动生成此变量(实际上是过程本身)?
答案 0 :(得分:1)
阵列是你正在寻找的。您可以创建一个可以容纳一系列变量的变量,而不是创建一个新的变量$ data {INDEX}。
例如,如果您想“推送”包含数据的数组,可以执行此操作。
$myData = array();
// appends the contents to the array
$myData[] = file_get_contents($url);
$myData[] = file_get_contents($url2);
阵列允许更多功能和效率。
您可以找到文档 here 。
完整的实现看起来像这样。
// create an array of requests that we want
// to load in the url.
$words = array('word', 'word2');
// we'll use this later on for loading the files.
$baseUrl = 'http://lema.rae.es/drae/srv/search?val=';
// string to replace in the head.
$cssReplace = '<style type="text/css"></style></head>';
// string to remove in the document.
$spanRemove = '<span class="f"><b>.</b></span>';
// use for printing out the result ID.
$resultIndex = 0;
// loop through the words we defined above
// load the respective file, and print it out.
foreach($words as $word) {
// check if the request with
// the given word exists. If not,
// continue to the next word
if(!isset($_REQUEST[$word]))
continue;
// load the contents of the base url and requested word.
$contents = file_get_contents($baseUrl . $_REQUEST[$word]);
// replace the data defined above.
$contents = str_replace('</head>', $cssReplace, $contents);
$contents = str_replace($spanRemove, '', $contents);
// print out the result with the result index.
// ++$resultIndex simply returns the value of
// $resultIndex after adding one to it.
echo '<div id="result', (++$resultIndex) ,'">', $contents ,'</div>';
}