循环遍历表单元素数组列表以获取或获取我们需要或想要保留的元素

问题描述 投票:-2回答:2

这是我目前的代码,我正在寻找一种更有效的编写方式。

需要使用foreach循环遍历每个变量或者以某种方式将它们全部添加到数组中,而不必重新编写每个变量名称。

$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;
php arrays loops foreach
2个回答
0
投票

如您所知,您希望保留的密钥可以执行以下操作:

<?php

/** 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;
?>

发生的事情是你循环通过你的$formValues并获得数组中每对的键和值。

然后对你的$keys_to_keep进行检查以查看当前元素是否是你想要保留的元素,如果是,那么你将它保存到$temp_array

阅读材料

foreach

in_array


-1
投票

您可以使用变量变量和foreach。

Foreach($formValues as $key => $var){
    $$key = $var;
}

Echo $relocation ."\n" . $europe;

https://3v4l.org/QeLjp

编辑我现在看到你的数组变量键并不总是与你想要的变量名相同。在这种情况下,您无法使用上述方法。 在这种情况下,您需要使用list()= array。

List($relocation, $europe) = $formValues;
// The list variables have to be in correct order I just took the first two for demo purpose.
© www.soinside.com 2019 - 2024. All rights reserved.