在复选框中显示JSON数组的机制

时间:2012-05-30 14:35:33

标签: php arrays json checkbox

我使用JSON创建一个多维数组。现在我的问题是如何制作一组复选框(例如表格或任何东西,以便通过水平条分隔它们。)

这是文件行的示例:

{"id": "v0", "namegroup": "Table rules create OR insert", "rule": "All classes give origin to a table.", "value": 0}

这就是我创建数组的方式:

<?php 
$file = fopen("rules.txt", "r") or exit("Unable to open file!"); 
$arrayRules = array();
$i = 0;
while(!feof($file))
{
    $line = fgets($file);
    $content = json_decode(utf8_encode($line), true);
    $arrayRules[$i]['id'] = $content["id"];
    $arrayRules[$i][0] = utf8_decode($content["rule"]);
    $arrayRules[$i]['namegroup'] = $content["namegroup"];
    $arrayRules[$i][1] = $content["value"];
    $i = $i + 1;
}
fclose($file);
?>

这就是我创建复选框的方式:

echo "<input name=\"regra[]\"  value=\"" . $arrayRules[$i]["id"] . "\" type=\"checkbox\"  /> " . $arrayRules[$i][0] . "<br/> "  ;

请记住,用户可以编辑组的名称和所有其他点。 你可以注意到,我的问题不是如何回显复选框,但是如何通过组来创建和组织复选框的机制。

UPDATE1

现在我有了这个:

for($i=0; $i < count($arrayRules); $i++)
{
    if ($arrayRules[$i]['idgroup'] == 1)
    {
        if  ($arrayRules[$i][1] == 1)
            echo  "<input name=\"regra[]\"  value=\"" . $arrayRules[$i]["id"] . "\" type=\"checkbox\" checked onclick=\"this.checked='checked'\"/> " . $arrayRules[$i][0] . "<br/> "  ;

        if ($arrayRules[$i][1] == 0)
            echo "<input name=\"regra[]\"  value=\"" . $arrayRules[$i]["id"] . "\" type=\"checkbox\"  /> " . $arrayRules[$i][0] . "<br/> "  ;
    }
}
?>

问题是if ($arrayRules[$i]['idgroup'] == 1)不应该是1,而应该是变量或者每当它在idgroup上的文件中找到新的或不同的名称时添加或创建新表/一组复选框。

1 个答案:

答案 0 :(得分:0)

将group_id param添加到您的json对象中并使用

 $arrayRules[$group_id][$i]

之后,您可以执行以下操作:

foreach($arrayRules as $group_id=>$objects) {
   // start group html
   foreach($objects as $i=>$params) {
       echo "<input name=\"regra[]\"  value=\"" . $params[$i]["id"] . "\" type=\"checkbox\"  /> " . $params[$i][0] . "<br/> "  ;
   }
   // end group html
}