在 PHP 中使用两个数组获取变量和值 ($key = $value)


Use two arrays to get variable and value ($key = $value) in PHP

$cfields = array_filter(explode(",", get_option('CComment_fields')));
$Ctlds = array_filter(explode(",", get_option('Ctlds')));

对不起,我知道这是一团糟。 基本上我最终得到两个数组:$cVal$Ctlds

数组:

$Cval = Array ( [0] => Fun Co [1] => 555-555-5555 [2] => test@test.com [3] => Tom [4] => Smith ) 
$Ctlds = Array ( [0] => user_company [1] => user_phone [2] => user_email [3] => user_firstname [4] => user_lastname )

我希望$Ctlds中的匹配[NUMBER]值是变量,$Cval中的匹配[NUMBER]是值。

例:user_company将被分配价值 Fun Couser_phone将被分配值 555-555-5555等。。

这是我尝试过的代码 - 糟糕,我知道。

foreach ($Ctlds as $Ctlds){
        $cVal[] = $Ctlds[];
    }

我已经尝试过我知道的代码是哇。 任何帮助将不胜感激。 对于搜索参考,这是使用数组在 PHP 中创建变量(键)和值。 非常感谢。

我不确定你想要什么,但你应该试试这个:

$result = array();
foreach ($Ctlds as $key => $Ctld) {
    $result[$Ctld] = $Cval[$key];
}

你会得到一个数组,比如:

Array (
    [user_company] => 'Fun Co',
    [user_phone] => '555-555-5555',
    [user_email] => 'test@test.com',
    [user_firstname] => 'Tom',
    [user_lastname] => 'Smith'
)

使用 array_combine . 这正是它的用途。

$result = array_combine($Ctlds, $Cval);

如果您希望它们是变量,则可以extract该数组。

尝试用逗号分隔数组并转义字符串。前任:

前任:

$Cval = array (
    [0] => "Fun Co",
    [1] => "555-555-5555",
    [2] => "test@test.com",
    [3] => "Tom",
    [4] => "Smith" ); 

此代码:

foreach ($Ctlds as $key => $Ctld) {
    $$Ctld = $Cval[$key];
}

将导致:

$user_company = "Fun Co";
$user_phone = "555-555-5555";
etc