2017-09-02 152 views
1

我在使用三元运算符设置数组索引时遇到问题。我想要做的是,如果语句满足if条件,我想添加一个额外的索引到我将用来从数据库中插入数据的数组。然而,每一个我用的是三元,如果运营商包括这些数组索引的时候,我总是得到一个错误三元运算符意外的T_DOUBLE_ARROW如果运算符

意外“=>” T_DOUBLE_ARROW

这里是我的代码:

$data = array('remark' => $this->input->post('remark'), 
      'rating' => $this->input->post('rating'), 
      ($_SESSION['user_type'] == 'Customer' ? 'user_id' => $_SESSION['id'] : ''), 
      ($_SESSION['user_type'] == 'Customer' ? 'food_item_id' => $this->input->post['refid'] : '')); 

任何人都知道如何解决这个问题?难道我做错了什么?任何帮助,将不胜感激

+0

@Qirel已经尝试在网页中提到的解决方案,但问题仍然存在 – Chamber

+0

由于双箭头是三元运算符内。这不是你如何动态地向数组添加元素的方法。 – Qirel

回答

0

这里是你应该使用它的方式:

$data = array('remark' => $this->input->post('remark'), 
      'rating' => $this->input->post('rating'), 
      'user_id' => ($_SESSION['user_type'] == 'Customer' ? $_SESSION['id'] : ''), 
      'food_item_id' => ($_SESSION['user_type'] == 'Customer' ? $this->input->post['refid'] : '')); 
0

移动三元如果功能上与=>后,像这样

$data = array(
      'remark'  => $this->input->post('remark'), 
      'rating'  => $this->input->post('rating'), 
      'user_id'  => $_SESSION['user_type'] == 'Customer' 
          ? $_SESSION['user_type'] 
          : '', 
      'food_item_id' => $_SESSION['user_type'] == 'Customer' 
          ? $this->input->post['refid'] 
          : '' 
      ); 
0

如果要动态地添加数据对于一个数组,如果条件不成立,如果不希望该键存在,则不应该使用这种三元运算符。通过在之后检查条件来单独添加它们,如果条件为真,则添加元素。

$data = array('remark' => $this->input->post('remark'), 
       'rating' => $this->input->post('rating')); 

if ($_SESSION['user_type'] == 'Customer') 
    $data['user_id'] = $_SESSION['id']; 
if ($_SESSION['user_type'] == 'Customer') 
    $data['food_item_id'] = $this->input->post['refid']; 

你仍然可以使用数组定义范围内的三元运算符,但你仍然会创建密钥(即使该元素为空值)

$data = array('remark' => $this->input->post('remark'), 
       'rating' => $this->input->post('rating'), 
       'user_id' => ($_SESSION['user_type'] == 'Customer' ? $_SESSION['id'] : ''), 
       'food_item_id' => ($_SESSION['user_type'] == 'Customer' ? $this->input->post['refid'] : '')); 
+0

我也尝试过使用该解决方案,但当我已经试图在数据库中插入数据时,出现'未知字段类型'错误 – Chamber

+0

如果您需要键中存在数组(未指定在问题中),那么你需要第二个代码片段。 – Qirel

+0

我指的是代码的第二部分,我收到了'未知字段类型'错误 – Chamber

1

你不能同时限定的阵列(你的方式)选择性地设置索引但可以使用array_filter删除不需要的索引你:

$data = array_filter(array(
    'remark' => $this->input->post('remark'), 
    'rating' => $this->input->post('rating'), 
    'user_id' => $_SESSION['user_type'] == 'Customer' ? $_SESSION['id'] : '', 
    'food_item_id' => $_SESSION['user_type'] == 'Customer' ? $this->input->post['refid'] : '', 
)); 

这种方式,阵列中的任何空字符串值将被重新在分配给$ data变量之前移动。

仅供参考,请参阅: