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 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法