简体   繁体   中英

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:

;           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):

<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).

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? 2. How to get the values from said table?

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.

In php, you want to have an array with this structure, generated from your CSV file, you probably already have this or something similar:

$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:

<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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM