【问题标题】:Is there a way to automate declaring variables in an array?有没有办法自动在数组中声明变量?
【发布时间】:2016-06-23 18:17:47
【问题描述】:

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

这存在吗?

【问题讨论】:

    标签: php arrays codeigniter object variable-declaration


    【解决方案1】:

    是的,

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

    【讨论】:

      【解决方案2】:

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

      $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

      【讨论】:

      • 太棒了,rchh,就是这样!我特别喜欢第二种选择,我不知道这是一种可能性。这将帮助我极大地简化我的代码......我有一种感觉,我对它过于冗长了。我将此答案标记为正确。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-19
      • 2013-06-27
      • 1970-01-01
      相关资源
      最近更新 更多