我有一个通过array_merge和json编码得到的结果数组,看起来像下面这样:
$c=[{"type":"textarea","label":"textarea","Element_Values":"cfgedrgyte","Element_Name":"textarea-201859","Count_Images":0,"req":0}, {"type":"dropdown","label":"dropdownbox","Element_Values":"d2","Element_Name":"dropdown-480200","Count_Images":0,"req":0,"choices":[{"label":"d1","sel":0},{"label":"d2","sel":0}]},
{"type":"sub-header","label":"section3","Element_Values":"-","Element_Name":"sub-header-327336","Count_Images":0,"req":0},{"type":"checkbox","label":"checkbox","Element_Values":"[\"c1\",\"c2\"]","Element_Name":"checkbox-483738","Count_Images":0,"req":0,"choices":[{"label":"c1","sel":0},{"label":"c2","sel":0}]}, {"type":"radio","label":"radio","Element_Values":"\"r2\"","Element_Name":"radio-824113","Count_Images":0,"req":0,"choices":[{"label":"r1","sel":0}, {"label":"r2","sel":0}]},
{"type":"description","label":"test template is here","Element_Values":"-","Element_Name":"description-764196","Count_Images":0,"req":0}]
如果类型是复选框或单选框,请获取Element_Values并根据Element_Values更改数组选项choices。
{"type":"checkbox","label":"checkbox","Element_Values":"[\"c1\",\"c2\"]","Element_Name":"checkbox-483738","Count_Images":0,"req":0,"choices":[{"label":"c1","sel":0},{"label":"c2","sel":0}]}
上面,元素值为c1和c2。然后我需要将sel更改为1。
"choices":[{"label":"c1","sel":1},{"label":"c2","sel":1}]}
这是另一种类型的单选按钮:
{"type":"radio","label":"radio","Element_Values":"\"r2\"","Element_Name":"radio-824113","Count_Images":0,"req":0,"choices":[{"label":"r1","sel":0},{"label":"r2","sel":0}]}
输出应该是:
{"type":"radio","label":"radio","Element_Values":"\"r2\"","Element_Name":"radio-824113","Count_Images":0,"req":0,"choices":[{"label":"r1","sel":0},{"label":"r2","sel":1}]}
我做了以下代码:
$c=json_decode($c);
foreach($c as $kc=>&$vc)
{
if( $vc['type']=="checkbox" || $vc['type']=="radio")
{
$Val=$vc['Element_Values'];
$choices=&$vc['choices'];
foreach($choices as $key=>&$val)
{
if($val['label']==$Val)
{
$val['sel']=1;
}
unset($val['sel']);
}
}
}
echo json_encode($c);
我知道我缺少的是一个简单的东西。请帮助我解决这个问题。先谢谢了!