简体   繁体   English

在if()之后为php中的大量变量赋值

[英]Assigning values to a large number of variables in php after an if ()

Do you know a better way to do thing when it comes to assigning values to a large number of variables after an if? 如果在if之后为大量变量赋值,您知道更好的处理方法吗?

In my case it like this: 就我而言,它是这样的:

$akeType = array_key_exists('type',$handle);
$akeParent = array_key_exists('parent',$handle);
$akeUserName = array_key_exists('userName',$handle);
$akeUserId = array_key_exists('userId',$handle);
$akeCountryCode = array_key_exists('userId',$handle);

if ( $akeType && $akeParent && $akeUserName && $akeUserId & $akeCountryCode ) {
$listType   = $handle['type'];
$listParent = $handle['parent'];
$listUserName = $handle['userName'];
$listUserId = $handle['userId'];
$foo = $_POST['foo'];
$bar = $_POST['bar'];
$listCountryCode = $handle['countryCode']; // Is there a way to clean up this part? The assignments to variables.

看一下extract -从数组将变量导入到当前符号表中

extract($handle, EXTR_OVERWRITE, "ake_");

You can do this with the somewhat more obscure code following: 您可以使用以下较为晦涩的代码来做到这一点:

$keys= array('type','parent','userName', 'userId');
foreach($keys as $key) {
    $nametoset= "list".ucfirst($key);
    $$nametoset= $handle[$key];
}

$$nametoset refers to the variable named like the string $nametoset . $$nametoset引用名为$nametoset的变量。 Similar code may be used for the $ake... variables. 类似的代码可用于$ake...变量。

You can use Variable variables to set your variable list . 您可以使用Variable变量来设置变量列表

For your specific case, you can use the following code: 对于您的特定情况,可以使用以下代码:

foreach ($handle as $key => $value) {
    $var_name = 'list'.$key;
    $$var_name = $value;
}

foreach ($_POST as $pkey => $pvalue) {
    $$pkey = $pvalue;
}

These loops create variables depending on your arrays keys. 这些循环根据您的数组键创建变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM