我昨天提交了一个问题,但我认为它太长且令人困惑。今天,我缩短了所有内容并提交了我的代码示例。代码背后的想法是解析内容,将内容插入到一个表单中,该表单将在本示例中回显或插入到 mysql 数据库中。该代码运行没有错误,但仅显示单个字母和数字而不是完整单词,请参阅下面的详细信息:
<?php
$fullstring = "Name: Steve - Age: 25, Name: Bob - Age: 30, Name: Amanda - Age: 18,"; // Content to be parsed
function get_string_between($string, $start, $end) {
$start = preg_quote($start);
$end = preg_quote($end);
$pattern = "~$start\s*(.*?)$end\s*~";
$match = preg_match_all($pattern, $string, $matches);
if ($match) {
return $matches[1];
}
}
$parsed1 = get_string_between($fullstring, "Name: ", "-");
$parsed2 = get_string_between($fullstring, "Age: ", ",");
////////// The form //////////////////////
echo '<form action="" method="POST">';
for ($i=0; $i < count($parsed1); $i++) {
echo "Name: <input name=\"name\" type=\"text\" value=\"". $parsed1[$i]. "\">","<br>" ;
echo "Age type: <input name=\"age\" type=\"text\" value=\"" . strip_tags($parsed2[$i]) . "\">","<br>" ;
}
echo '<input type="submit" name="submit" value="submit">';
echo '</form>';
if (isset($_POST['submit'])) {
$i = 0;
foreach ($_POST as $value) {
$name = $_POST['name'][$i];
$age = $_POST['age'][$i];
echo $name.'....'.$age.'<br>';
$i++;
}
}
//// mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
//////////////////////////////////////////////////////////////
?>
当我按下提交时,我得到了回显:
A....1
m....8
a....
Instead of of all the names in the in the form.
非常感谢大家的帮助。
最佳答案
您可以使用name[]
和age[]
echo '<form action="" method="POST">';
for ($i=0; $i < count($parsed1); $i++) {
echo "Name: <input name=\"name[]\" type=\"text\" value=\"". $parsed1[$i]. "\">","<br>" ;
echo "Age type: <input name=\"age[]\" type=\"text\" value=\"" . strip_tags($parsed2[$i]) . "\">","<br>" ;
}
echo '<input type="submit" name="submit" value="submit">';
echo '</form>';
if (isset($_POST['submit'])) {
foreach($_POST['name'] as $k=>$name){
echo $name.'.... Age:'. $_POST['age'][$k];
}
}
关于php - 无法正确回显数组中的数据。 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20834323/