Turning an array element into a link, which acts like a “POST” method in a form.

ⅰ亾dé卋堺 提交于 2020-01-03 03:10:31

问题


I have a webpage which contains a form, like the following:

<Form action=”search.php” method=”POST”>
<fieldset>
<legend> Enter your search below </legend>
<textarea name=”query”> </textarea>
</fieldset>
</form>

The users text is read from query and search results are displayed using code in the following section:

if ($_POST['query'])
{
//Users query is read and results from a search API are displayed
}

The next thing that happens is that a list of synonyms are generated, stored in a multidimensional array called $synonyms which I have displayed in a left-hand-navigation bar, using the code shown below. $newline prints a newline (as the variable name suggests)

Example of a $synonyms array:

array(3) 
{ [0]=> array(2) 
    { [0]=> string(9) "chelonian" 
      [1]=> string(17) "chelonian reptile" } 

 [1]=> array(6) 
{ [0]=> string(7) "capsize" 
  [1]=> string(11) "turn turtle" 
  [2]=> string(8) "overturn" 
  [3]=> string(9) "turn over" 
  [4]=> string(8) "tip over" 
  [5]=> string(9) "tump over" } 

 [2]=> array(4) 
 { [0]=> string(4) "hunt" 
   [1]=> string(3) "run" 
   [2]=> string(9) "hunt down" 
   [3]=> string(10) "track down" } 

}

Code used to output the array:

foreach ($synonyms as $test)
{   foreach ($test as $test2)
    {
    echo $test2.$newline.$newline;
    }
}

What I want to happen is:

Turn each synonym into a clickable link..if the user clicks the synonym "capsize", the word capsize is sent to the section where the synonym(previously query) is read and processed into results.. ie. back to this section:

if ($_POST['query'])
{
// Synonym is read and results from a search API are displayed
// Previously 'query' was read here
// The cycle continues again
}

Any ideas or suggestions on this one would be great, thanks guys.


回答1:


You should use GET in search form. Then list synonyms as shown below

foreach ($synonyms as $test)
{   foreach ($test as $test2)
    {
     // I used <br/> for newline
     printf('<a href="search.php?query=%1$s">%1$s</a><br/>', $test2);
    }
} 

Edit: And obviously, you should replace $_POST['query'] with $_GET['query']



来源:https://stackoverflow.com/questions/17751202/turning-an-array-element-into-a-link-which-acts-like-a-post-method-in-a-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!