2017-08-23 13:02
浏览 61


This is my current code, I'm looking for a more efficient way of writing it.

Need something like looping through each variable with a foreach or adding them all to an array somehow, without me having to re-write every variable name.

$formValues = $form_state->getValues();    

$relocation = $formValues['relocation'];
$europe = $formValues['europe'];
$twoyears = $formValues['twoyears'];
$realestate = $formValues['realestate'];
$nominated = $formValues['check_nominated_by'];
$nom_comp = $formValues['nom_company'];
$nom_contact = $formValues['nom_contact'];
$nom_email = $formValues['nom_email'];
$contact1 = $formValues['contact1'];
$position1 = $formValues['contact_position1'];
$email1 = $formValues['email1'];
$contact2 = $formValues['contact2'];
$position2 = $formValues['contact2'];
$email2 = $formValues['contact2'];
$contact3 = $formValues['contact3'];
$position3 = $formValues['contact3'];
$email3 = $formValues['contact3'];

tempstore = array();
$tempstore['relocation'] = $relocation;
$tempstore['europe'] = $europe;
$tempstore['twoyears'] = $twoyears;
$tempstore['realestate'] = $realestate;
$tempstore['membertype'] = $membertype;
$tempstore['nominated_by'] = '';
// All other fields need to be in this array too
// But there are a lot of unwanted fields in the $formValues
$_SESSION['sessionName']['formName'] = $tempstore;
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanfan9859 2017-08-23 13:12

    Seeing as you know the keys you'd like to keep you can do the following:

    /** The keys you want to keep... **/
    $keys_to_keep = [
    /** Will be used to store values for saving to $_SESSION. **/
    $temp_array = [];
    /** Loop through the keys/values. **/
    foreach ($formValues as $key => $value) {
        /** The correct key i.e. the key you'd like to save. **/
        if (in_array($key, $keys_to_keep)) {
            /** What you wish to do... **/
            $temp_array[$key] = $value;
    $_SESSION['sessionName']['formName'] = $temp_array;

    What is happening is that you are looping through your $formValues and getting both the keys and values of each pair in the array.

    Then an check is being done against your $keys_to_keep to see if the current element is the one you wish to keep, if it is then you save it in to $temp_array.

    Reading Material



    点赞 打赏 评论
  • douwen2158 2017-08-23 13:14

    You can use variable variables and a foreach.

    Foreach($formValues as $key => $var){
        $$key = $var;
    Echo $relocation ."
    " . $europe;


    Edit I see now that your array variable keys are not always the same as the variable name you want. In that case you can't use the method above.
    In that case you need to use list() = array.

    List($relocation, $europe) = $formValues;
    // The list variables have to be in correct order I just took the first two for demo purpose.
    点赞 打赏 评论

相关推荐 更多相似问题