2016-01-05 18:26
浏览 238


How would I convert a json string that contains checkbox values to a list?

For example, I have the following json string : {"User1":"Checked","User2":"","User3":"Checked"}

I want to pull a list from the above data, and assign it to a variable. The list should of course, only output the checked elements as such :

User1 User3

and ignore the unchecked items.

Is this possible?

Original thought was to do this in a jqgrid layout, original question here :

Full Array Code(processing side) :

$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.

I then save $statusd into my db whenever anyone updates the form, but no data is transferred.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzice4895 2016-01-05 18:31

    Decode the JSON to an array, then get the keys where the value equals 'Checked':

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

    Or possibly to filter out empty items instead of searching for 'Checked', but then you still have keys instead of values:

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

    Then implode() or foreach() or whatever to work with the array.

    Based on your edits:

    1. You really should use a related table and save each user to a new row, but
    2. You're encoding then adding slashes mysqli_real_escape_string and then trying to decode it again

    Assuming you're not going to do #1 then just this:

    $statusd = mysqli_real_escape_string($this->_con,
                                         implode(",",  array_keys($status_array, 'Checked')));
    解决 无用
    打赏 举报

相关推荐 更多相似问题