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

Is there a way to automate declaring variables in an array?

我正在学习 PHP 并在 Codeigniter 中工作。当我制作数据数组并声明函数所需的变量时,我觉得我在重复输入类似的东西(重复工作)。

这是一个例子:

  //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));

我正在寻找一种方法来自动声明 dropdowndata 数组中的所有变量。我正在寻找类似的东西,对于每个键,根据以下模式声明变量。

这个存在吗?

我不确定我是否完全理解你想要什么...但是你可以将数组键转换为局部变量...

$array = ['x' => 1, 'y' => 2];
extract($array);
var_dump($x);
var_dump($y);

php test.php

int(1)

int(2)

参考:http://php.net/manual/en/function.extract.php

是的,

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

但不确定为什么你需要这些作为变量...为什么不直接使用 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']));