0

我的表单中有 3 个文本区域来收集姓名、年龄和地点,并在提交表单后回显输出。

我面临的问题:

例如,如果我输入如下数据

姓名 :

George
Tom

年龄:

30
40

地方:

SA
IN

我期待这样的输出:

My name is George, age 30, from SA
My name is Tom, age 40, from IN

但它给了我输出:

My name is George, age 30, from SA
My name is George, age 30, from IN
My name is George, age 40, from SA
My name is George, age 40, from IN
My name is Tom, age 30, from SA
My name is Tom, age 30, from IN
My name is Tom, age 40, from SA
My name is Tom, age 40, from IN

如何处理来自每个 textarea 的每一行数据并给出输出?

我的代码: PHP FIDDLE

<form  id="main" name="main" action="#text" method="post" > 
<div class="input">Name<span><textarea  class="textarea" id="main-name" name="main-name" type="text"></textarea></span> </div>
<div class="input">Age<span><textarea  class="textarea" id="main-age" name="main-age" type="text"></textarea></span> </div>
<div class="input">Place<span><textarea  class="textarea" id="main-place" name="main-place" type="text"></textarea></span> </div>   


<div class="submit-clear">
            <input  id="generate" type="submit"  name="script" value="create my symcli script" />
            <input onClick="clear_all();"  id="clear" type="submit" name="clear" value="clear" />   
</div>
</form>



<div id="output-main">
<form id="main2" name="main2" action="#text" method="post">
<textarea onclick="this.select()" name="output_textarea" id="output_textarea" cols="100" rows="25" readonly value=" ">

<?php
$names1 = $_POST['main-name'];
$ages1 = $_POST['main-age'];
$places1 = $_POST['main-place'];

$names = explode("\n", $names1); 
$ages = explode("\n", $ages1); 
$places = explode("\n", $places1); 

                foreach ($names as $key => $name) {
                foreach ($ages as $key => $age) {
                foreach ($places as $key => $place) {
                $name = trim($name); 
                $age = trim($age);
                $place = trim($place);


                echo "My name is $name, age $age, from $place".PHP_EOL;

                }}}


?>

</textarea>

</form>

</div>
4

2 回答 2

1

foreach 在这里是错误的循环结构。您实际上所做的只是呼应所有可能的条目组合。

使用简单的 for 循环,以便每个条目只处理一次,而不是 2^(entries - 1) 次(=> 每个可能的组合)。

$names = explode("\n", $_POST['main-name']);
$ages = explode("\n", $_POST['main-age']);
$places = explode("\n", $_POST['main-place']);

$entries = min(count($names), count($ages), count($places))

for ($i = 0; $i < $entries; $i++) {
    $name = trim($names[$i]); 
    $age = trim($ages[$i]);
    $place = trim($places[$i]);

    echo "My name is $name, age $age, from $place".PHP_EOL;
}
于 2013-10-13T14:51:21.117 回答
0

如果您有相同的姓名、年龄和位置值计数。你可以试试这个。

 foreach ($names as $key => $name) {
            $name = trim($name); 
            $age = trim($ages[$key]);
            $place = trim($places[$key]);


            echo "My name is $name, age $age, from $place".PHP_EOL;

           }

否则,您需要像这样关联数组 array[0]['name'], array[0]['age'], array[0]['place']。这将是理想的选择。

于 2013-10-13T15:02:02.843 回答