-2

我希望能够写的是一个字符串,它是一个数组,它将存储在数据库中的 jason 字符串中。我的代码遍历复选框,但我希望能够测试 $input 名称是否为“interests”

<input type="checkbox" name="interests[]" value="dvd" />` <-- checkbox lists

我无法得到的另一件事是在每个 $ 值周围加上引号,例如“dvd”、“computers”

$interests = '[';
$count = 1;
$counter = count($_POST["interests"]);
foreach($_POST as $checkbox => $input) {
    if(is_array($input)) {
    // test here is input is "interests"    
        foreach($input as $index => $value) {   
            $interests .= /*quote here*/ $value /*quote here*/ .= ($count < $counter) ? ',' : '';
            $count += 1;
        }
    }
}
$interests .= ']';
echo $interests;

兴趣是假设写出[“dvd”,“计算机”,“硬盘驱动器”],但它只写出[dvd,计算机,硬盘驱动器]

4

3 回答 3

1
$_POST["interests"] = array("dvd", "computers", "hard drives");
$interests = '["' . implode('","', $_POST["interests"]) . '"]';
echo $interests;

看到它在行动

于 2013-02-08T07:12:23.443 回答
0

使用json_encode()而不是手动创建 JSON:

echo json_encode($_POST['interests']);

输出

[“DVD”,“电视”,“收音机”]

于 2013-02-08T07:12:47.040 回答
0

试试这个,

$interests = '';
$count = 1;
$counter = count($_POST["interests"]);
foreach($_POST as $checkbox => $input) {
    if(is_array($input)) {
    // test here is input is "interests"    
        foreach($input as $index => $value) {   
            $interests .= $value .= ($count < $counter) ? ',' : '';
            $count += 1;
        }
    }
}
$interests = json_encode($interests);
echo $interests;
于 2013-02-08T07:17:29.397 回答