0

I have a text area in my html form.I am collecting the data from this form using POST method.Here I need to set a blank line as a boundary to repeat a function using this form data. for example I am calculating the sum of the digits which are collected from this text area using below code

<?php
$devices = $_POST['devs'];
$count = array_sum(explode("\n", $devices));
echo "sum is $count";
?>

If I enter below digits

1
2
3

I will get output like:

sum is 6

and what I need is, if I put digits like

1
2
3

4
5
6

I need output like

sum is 6
sum is 15

how can I do it ?

4

1 回答 1

1

如果您的数据中没有任何额外的空格,这可以与您当前的方法非常相似地完成,方法是添加一个额外的步骤以在两个换行符上展开,然后在每个部分上调用您当前的代码:

$devices = $_POST['devs'];
$repeats = explode(PHP_EOL.PHP_EOL, $devices); // Favor PHP_EOL (end of line) to avoid cross OS issues
foreach($repeats as $repeat)
{
  $count = array_sum(explode(PHP_EOL, $repeat));
  echo "sum is $count".PHP_EOL;
}

显然,如果有额外的空格,那么你需要先做一个清理步骤。

于 2013-08-05T17:51:38.020 回答