更新时间:2023-01-30 21:29:38
您的代码仅向数据库中插入单个字符的原因是,您使用json_encode()
将数组$_POST['data_1']
转换为字符串,然后尝试访问以后将此字符串作为数组.
The reason why your code only inserts single characters to the database is because you convert the array $_POST['data_1']
to a string using json_encode()
and then try to access this string as an array later.
当您访问带有方括号表示法的字符串(在您的代码:$data_1[$idx]
中)时,PHP会将其解释为字符串中的字符访问,仅产生一个字符.
When you access a string with the square brackets notation (in your code: $data_1[$idx]
), PHP interprets this as a character-access in the string, resulting in only a single character.
从 PHP手册:
可以使用方数组括号在字符串后指定所需字符的从零开始的偏移量,来访问和修改字符串中的字符,如
$str[42]
所示.为此,可以将字符串视为字符数组.
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in
$str[42]
. Think of a string as an array of characters for this purpose.
看看这个工作示例:
<form method="post">
<input name="data_1[]" value="1111111111">
<input name="data_1[]" value="2222222222">
<input name="static[]" value="12">
<input name="data_1[]" value="3333333333">
<input name="data_1[]" value="4444444444">
<input name="static[]" value="34">
<input name="data_1[]" value="5555555555">
<input name="data_1[]" value="6666666666">
<input name="static[]" value="56">
<input type="submit">
</form>
<?php
$data = array();
$data_1 = $_POST['data_1'];
$static = $_POST["static"];
foreach($static as $idx=>$val){
$data[] = array(
'data_1' => json_encode(Array($data_1[$idx*2],$data_1[$idx*2+1])),
'static' => $static[$idx]
);
}
echo "<pre>";
print_r($data);
?>