如何从多个复选框帖子值中对结果进行排列?

时间:2022-06-26 13:22:05

I am building a fruit store website.

我正在建立一个水果店网站。

Currently, I wanna ask to my customers what kind of fruits they love.

目前,我想向顾客询问他们喜欢什么样的水果。

So, I created several checkbox options for them.

所以,我为他们创建了几个复选框选项。

<form action='customer_favorite' method='POST'>
  <input type='checkbox' name='chk[]' value='banana' />
  <input type='checkbox' name='chk[]' value='mango' />
  <input type='checkbox' name='chk[]' value='apple' />
  <input type='checkbox' name='chk[]' value='orange' />
  <input type='checkbox' name='chk[]' value='kiwi' />
<input type='submit' value='submit' />
  • I don't know how many checkboxes they will check.

    我不知道他们会检查多少个复选框。

  • When it posts to my server, I want to get the result like this.

    当它发布到我的服务器时,我想得到这样的结果。

    apple, orange, kiwi
    
  • second customer would choose four of them.

    第二个客户会选择其中四个。

    banana, mango, apple, orange
    

and I will put this data into my db like this.

我会像这样把这些数据放到我的数据库中。

$data = array(
'fav_fruits' = $this->input->post('chk')
);    

$this->db->insert('customer', $data)

The problem is that I can't get result 'apple, orange, kiwi' like this.

问题是我无法得到像这样的结果'apple,orange,kiwi'。

  • we don't know how many checkbox values will be there.
  • 我们不知道会有多少个复选框值。
  • I want to array values like this 'apple, orange, kiwi'
  • 我想要像'apple,orange,kiwi'这样的数组值

2 个解决方案

#1


2  

If you want the clear text values in your DB (not normalized), you can do this:

如果您想要数据库中的明文值(未规范化),您可以这样做:

$data = array(
    'fav_fruits' = json_encode($this->input->post('chk'))
);    
$this->db->insert('customer', $data)

EDIT: changed teh original implode() to json_encode due to @Madmartigan comment

编辑:由于@Madmartigan评论,将原始的implode()更改为json_encode

#2


1  

You will get result in array with name of your checkbox .In this case you will get like chk[0]=> , chk[1] => , and so on.. in $_POST array.

你将得到带有复选框名称的数组结果。在这种情况下,你会得到chk [0] =>,chk [1] =>,依此类推..在$ _POST数组中。

After that if u have to store it like banana, mango, apple, orange then , do implode of that array using ',' separator..

之后,如果你必须像香蕉,芒果,苹果,橙子那样存储它,那么使用','分隔符来破坏那个数组。

implode(',' $_POST['chk'])

#1


2  

If you want the clear text values in your DB (not normalized), you can do this:

如果您想要数据库中的明文值(未规范化),您可以这样做:

$data = array(
    'fav_fruits' = json_encode($this->input->post('chk'))
);    
$this->db->insert('customer', $data)

EDIT: changed teh original implode() to json_encode due to @Madmartigan comment

编辑:由于@Madmartigan评论,将原始的implode()更改为json_encode

#2


1  

You will get result in array with name of your checkbox .In this case you will get like chk[0]=> , chk[1] => , and so on.. in $_POST array.

你将得到带有复选框名称的数组结果。在这种情况下,你会得到chk [0] =>,chk [1] =>,依此类推..在$ _POST数组中。

After that if u have to store it like banana, mango, apple, orange then , do implode of that array using ',' separator..

之后,如果你必须像香蕉,芒果,苹果,橙子那样存储它,那么使用','分隔符来破坏那个数组。

implode(',' $_POST['chk'])