[英]How to select string from an array of strings or a csv?
I need to create a website for a club which displays the relation between to items from a drop-down-menu. 我需要为一个俱乐部创建一个网站,该网站显示下拉菜单中各项之间的关系。 As example we take rock-paper-scissors.
例如,我们用剪刀石头布。 The data would be given by a .csv file, as an example the following .csv:
数据将由.csv文件提供,例如以下.csv文件:
; Stone; Scissors; Paper
Stone; Nothing happens.; Scissors get scattered.; Paper wraps stone.
Scissors; Stone scatters Scissors.; Nothing happens.; Paper gets cut.
Paper; Stone gets wrapped.; Scissors cut Paper.; Nothing happens.
I need to read the .csv and generate the select statements (first one for first row, second one for first column), which would end up like this (2x): 我需要阅读.csv并生成select语句(第一行用于第一行,第二行用于第一列),其结果将是这样(2x):
<b>Your Choice:</b>
<select id="yours" onchange="battle()">
<option style="display:none" disabled selected value> -- select an option --
</option>
<option>Stone</option>
<option>Scissors</option>
<option>Paper</option>
</select>
To this point, I got all this running in .php (read the csv, generate dropdowns). 至此,我在.php中运行了所有这些文件(阅读csv,生成下拉列表)。
Now comes the point where I am unsure about the proper, web-dev way of doing things: 1. How to store the table whithin the output of the pho script, so I can access it cleanly using js? 现在,我不确定正确的Web开发方法:1.如何在pho脚本的输出中存储表,以便可以使用js进行干净访问? 2. How to get the values from said table?
2.如何从所述表中获取值?
Pseudocode-solution: 伪代码的解决方案:
<script>
<my clean array data>
function battle() {
var x = document.getElementById("yours").value;
var y = document.getElementById("opponent").value;
var result = array.select(mine = x, opponent = y)
document.getElementById("result").innerHTML = result;
}
</script>
Setting up a javascript object with your table values would be a simple way to solve this. 用表值设置一个javascript对象将是解决此问题的一种简单方法。
In php, you want to have an array with this structure, generated from your CSV file, you probably already have this or something similar: 在php中,您希望有一个具有此结构的数组,该数组是从CSV文件生成的,您可能已经具有此数组或类似的东西:
$a = [
"Stone" => [
"Stone" => "Nothing Happens.",
"Scissors" => "Scissors get scattered (shattered?).",
"Paper" => "Paper wraps stone."
],
// ... "Scissors" and "Paper" go here
];
Then you need to write out a line of javascript encoding the php array into a javascript object: 然后,您需要写出一行javascript,将php数组编码为javascript对象:
<script>
var resultsTable = <?php echo json_encode($a); ?>;
</script>
Then your battle function becomes: 然后,您的战斗功能将变为:
function battle() {
var x = document.getElementById("yours").value;
var y = document.getElementById("opponent").value;
var result = resultsTable[x][y];
document.getElementById("result").innerHTML = result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.