PHP 将 $_POST 值转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9841759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP convert $_POST values to string
提问by bikey77
I'd like to be able to convert all post data to a string but keep only the values in a string variable.
我希望能够将所有发布数据转换为字符串,但只保留字符串变量中的值。
So if my posted data looks like this:
因此,如果我发布的数据如下所示:
Array ( [alloy] => Array ( [0] => K18 [1] => )
[color] => Array ( [0] => Gold [1] => )
[stone] => Array ( [0] => Diamond [1] => )
[dimension] => Array ( [0] => 3cm [1] => )
[button1] => Submit )
i'd like it to finally look like: $data = 'K18, color Gold, Diamond, 3cm';
我希望它最终看起来像: $data = 'K18, color Gold, Diamond, 3cm';
I've tried serialize, imploding array, http_build_query but they're not what I need.
我试过序列化、内爆数组、http_build_query,但它们不是我需要的。
if it helps to get the whole idea, I'm collecting data from 4 groups of checkbox and radiobutton arrays and I'd like to put the selected values into a delimited string and save to my db.
如果它有助于获得整个想法,我正在从 4 组复选框和单选按钮数组中收集数据,我想将选定的值放入一个分隔的字符串中并保存到我的数据库中。
采纳答案by dotoree
Maybe this is what you need:
也许这就是你需要的:
$s = array();
foreach ($_POST as $k => $v) {
if (is_array($v)) {
if ('color' === $k) {
array_push($s, implode('', array($k, $v[0])));
} else {
array_push($s, $v[0]);
}
}
}
echo implode(', ', $s);
回答by Máthé Endre-Botond
Here's a little trick. When grouping use name[]
instead of name
. This way the $_POST["name"] variable will be an array, just as you want.
这里有一个小技巧。分组时使用name[]
而不是name
. 这样 $_POST["name"] 变量将是一个数组,就像你想要的那样。
Example:
例子:
<input type="checkbox" name="inputname[]" value="1" />
<input type="checkbox" name="inputname[]" value="2" />
<input type="checkbox" name="inputname[]" value="3" />
PHP
PHP
print_r($_POST['inputname']);
// output if all checked
// 如果所有检查都输出
Array
(
[0] => 1
[1] => 2
[2] => 3
)
NOTE: The array will contain only the checked values
注意:数组将只包含选中的值