2016-06-23 6 views
0

私は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アレイ内のすべての変数の宣言を自動化する方法を探しています:ここで

は一例です。私は、各キーのために、次のパターンに従って変数を宣言するようなものを探しています。

これはありますか?

答えて

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

+0

恐ろしい、rchh、それはそれです!私は特に、私が知らなかった第二の選択肢が好きです。これは私のコードを合理化するのに大いに役立ちます....私はそれについてあまりにも冗長であると感じていました。私はこの答えを正しいものとしてマークしました。ありがとうございました! – Cyclist

関連する問題