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

时间:2016-06-23 18:17:47

标签: php arrays codeigniter object variable-declaration

我正在学习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数组中的所有变量。我正在寻找类似的东西,对于每个键,根据以下模式声明变量。

这是否存在?

2 个答案:

答案 0 :(得分:0)

我不确定我完全理解你想要的东西......但你可以把数组键变成局部变量......

$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

答案 1 :(得分:0)

叶,

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

但不确定为什么你需要这些作为变量...为什么不只是用作:

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