douhao2026 2016-06-23 18:17
浏览 64
已采纳

有没有办法自动声明数组中的变量?

I'm learning PHP and working in Codeigniter. I feel that I am typing similar things over again (duplicating work) when I am making data arrays and declaring the variables I need for functions.

Here is an example:

  //MAKE ARRAY OF USER ANSWERS TO QUESTIONS
    $dropdowndata = array
    (   'user_socialhour' => $this->input->post('socialhour'),
        'user_socialpm' => $this->input->post('socialpm'),
        'user_eventhour' => $this->input->post('eventhour'),
        'user_eventpm' => $this->input->post('eventpm');

    //DECLARE THE VARIABLES I NEED FOR FUNCTIONS
         $user_socialhour = $this->input->post('socialhour');
        $user_socialpm = $this->input->post('socialpm');
        $user_eventhour = $this->input->post('eventhour');
        $user_eventpm = $this->input->post('eventpm');

     $calculateddata = array
    ('user_mornafteve' => $this->mornafteve($user_socialhour, >$user_socialpm), 'user_beforeafter' => $this->beforeafter($user_socialpm, >$user_eventpm, $user_socialhour, $user_eventhour));

I am looking for a way to automate the declaration of all the variables in the dropdowndata array. I am looking for something like, for each key, declare the variables according to the following pattern.

Does this exist?

  • 写回答

2条回答 默认 最新

  • dpvp56187 2016-06-23 18:28
    关注

    Ye,

    foreach($dropdowndata as $key=>$value) {
        $$key = $this->input->post(substr($key, 5))
    }
    

    But not sure why you need these as variables at all... why not just use as:

    //MAKE ARRAY OF USER ANSWERS TO QUESTIONS
        $dropdowndata = array(   
            'user_socialhour' => $this->input->post('socialhour'),
            'user_socialpm' => $this->input->post('socialpm'),
            'user_eventhour' => $this->input->post('eventhour'),
            'user_eventpm' => $this->input->post('eventpm');
    
        $calculateddata = array(
            'user_mornafteve' => $this->mornafteve($dropdowndata['user_socialhour'], $dropdowndata['user_socialpm']), 
            'user_beforeafter' => $this->beforeafter($dropdowndata['user_socialpm'], $dropdowndata['user_eventpm'], $dropdowndata['user_socialhour'], $dropdowndata['user_eventhour']));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动