【问题标题】:How to convert json checked checkbox data to a list?如何将 json 选中的复选框数据转换为列表?
【发布时间】:2016-01-05 18:26:46
【问题描述】:

如何将包含复选框值的 json 字符串转换为列表?

例如,我有以下 json 字符串: {"User1":"Checked","User2":"","User3":"Checked"}

我想从上面的数据中提取一个列表,并将其分配给一个变量。该列表当然应该只输出选中的元素:

用户 1 用户3

并忽略未选中的项目。

这可能吗?

最初的想法是在 jqgrid 布局中执行此操作,原始问题在这里: https://stackoverflow.com/questions/34615244/best-way-to-do-jqgrid-with-json-strings

全数组代码(处理端):

$status = $data['data-invoice-status']; // this is an array
                $status_array = array(); // create new array
                $status_names = array(1 => "Service Call",2 => "Estimate",3 => "Bid Accepted",4 => "Unstaged",5 => "Staged",6 => "Assigned",7 => "In Progress",8 => "Job Complete",9 => "Billed");
                for($i = 1; $i <= 9; $i++){ // loop from 1 to 5
                if(in_array($i, $status)){ // if value exists (has been selected), stack 'checked', if not, stack ''.
                    $status_array[$status_names[$i]] = "checked";
                } else {
                    $status_array[$status_names[$i]] = "";
                }
                }
                $status_json = mysqli_real_escape_string($this->_con, json_encode($status_array)); // encode the array into JSON and then escape it.

然后,每当有人更新表单但没有数据传输时,我都会将 $statusd 保存到我的数据库中。

【问题讨论】:

    标签: php json checkbox


    【解决方案1】:

    将 JSON 解码为数组,然后获取值等于 'Checked' 的键:

    $list = array_keys(json_decode($json, true), 'Checked');
    

    或者可能过滤掉空项目而不是搜索“已检查”,但是您仍然有键而不是值:

    $list = array_filter(json_decode($json, true));
    

    然后是 implode()foreach() 或任何与数组一起使用的东西。

    根据您的修改:

    1. 您确实应该使用相关表并将每个用户保存到新行,但是
    2. 您正在编码,然后添加斜杠mysqli_real_escape_string,然后尝试再次解码

    假设您不打算执行 #1,那么就这样做:

    $statusd = mysqli_real_escape_string($this->_con,
                                         implode(",",  array_keys($status_array, 'Checked')));
    

    【讨论】:

    • 好的,我尝试了您的代码,多种方式,但无法开始工作。这就是我想要做的,我不知道如何将我的 {"User1":"checked","User2":""} 翻译成通过链接编程的 jqgrid,我将在我的问题中添加,所以我想只是将它指向一个正常的输出 sql(this question) 如果有一种方法可以使用 jqgrid,那将是我的偏好,但从 LAIC(看它弯曲)的角度来看,这个也是如此。 (抱歉说错话了)
    • 我尝试了以下代码:$statusa = array_keys(json_decode($status_json, true)); $statusd = implode(",", $statusa);它返回null并且不保存?
    • 您需要更详细地更新您的问题,并且完全希望输出是。
    • 向问题添加了更新的代码。您正在寻找任何具体的细节吗?
    • 这保存了一个名为“checked”的值,但没有别的。如果有帮助,我将添加我的数组代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 2014-06-28
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多