我已经通过bootstrap表单构建器构建了一个表单,该表单构建器有两个复选框组,其中第一组有6个复选框&第二个是有5个复选框。当我填写表格时,以下列方式发布值。
{
"Hobbies#14287284244583705#reading": "Reading"
},
{
"Hobbies#14287284244603527#sports": "Sports"
},
{
"Hobbies#14287284244603819#dancing": "Dancing"
},
{
"Hobbies#142872842446043#watching_tv": "Watching TV"
},
{
"Hobbies#14287284244614612#swimming": "Swimming"
},
{
"Hobbies#14287284244611702#meeting_new_people": "Meeting new people"
},
{
"Education#14287284244615059#bachelors": "BAchelors"
},
{
"Education#14287284244629279#masters": "MAsters"
},
{
"Education#1428728424462974#ms": "MS"
},
{
"Education#14287284244629849#surgeon": "Surgeon"
},
{
"Education#14287284244622498#matric": "Matric"
}
现在我将它存储在我的mongodb数据库中,因为$ key = $ value。但是我在网格视图中显示它时遇到了问题。
我尝试用所有可能的方法对其进行分组,但如果复选框组增加,代码变得过于复杂,则无法轻松实现。如果键是相同的,PHP中是否有任何合并值的函数?
最终输出应该是:
{ "Hobbies":"Reading, Sports, Dancing.....(so on)},
{ "Education":"Masters, .... "}
以上关键方面。目前所有键都不同但我可以通过爆炸功能进行比较可能会爆炸[0]
答案 0 :(得分:0)
您应该在HTML代码中为所有爱好复选框使用数组命名,如下所示:
<input type="checkbox" name="Hobbies[] value="Reading"/><label>Reading</label>"
<input type="checkbox" name="Hobbies[] value="Sports"/><label>Sports</label>"...
与教育复选框相同。
现在你想print_r($_POST['Hobbies'])
。这将为您提供所需的输出。
答案 1 :(得分:0)
我认为Ashwani是对的,但是如果仍然希望将对象分组在第一个关键元素上,你可以这样做:
$a = json_decode('[{
"Hobbies#14287284244583705#reading": "Reading"
},
{
"Hobbies#14287284244603527#sports": "Sports"
},
{
"Hobbies#14287284244603819#dancing": "Dancing"
},
{
"Hobbies#142872842446043#watching_tv": "Watching TV"
},
{
"Hobbies#14287284244614612#swimming": "Swimming"
},
{
"Hobbies#14287284244611702#meeting_new_people": "Meeting new people"
},
{
"Education#14287284244615059#bachelors": "BAchelors"
},
{
"Education#14287284244629279#masters": "MAsters"
},
{
"Education#1428728424462974#ms": "MS"
},
{
"Education#14287284244629849#surgeon": "Surgeon"
},
{
"Education#14287284244622498#matric": "Matric"
}]', true);
$hash = array();
$out = array();
foreach($a as $n => $nod) $hash[explode('#',key($nod), 2)[0]][] = $nod[key($nod)];
foreach($hash as $k => $v) $out[$k] = implode(',', $v);
var_dump($out);