简体   繁体   English

键/值对作为 PHP 中的变量

[英]Key/Value pair as variable in PHP

I'm have parsed a csv file into a associative array which looks like this:我已将 csv 文件解析为关联数组,如下所示:

array(5) {
[0]=>  array(13) { 
            ["First Name"]=>string(7) "Name"
            ["Last Name"]=>string(14) "Last name"
            ["Login"]=>string(22) "name.lastname"
            ["Email"]=>string(27) "email"
…

I now want to write the value of each key into a variable with the name of the key, eg:我现在想将每个键的值写入一个带有键名的变量,例如:

$FirstName = "Name";
$LastName = "Last name";

As I am relatively new to programming and php I am struggling with this and I hope that you can give me a hint由于我对编程和 php 比较陌生,因此我正在为此苦苦挣扎,希望您能给我一个提示

Edit: This is how I create the array:编辑:这就是我创建数组的方式:

function csv_to_array($filename='', $delimiter=';')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}

$a_csv = csv_to_array($file, ';');

If your array was like this如果你的数组是这样的

array(5) {
[0]=>  array(13) { 
            ["foo"]=>string(7) "fooValue"
            ["bar"]=>string(7) "barValue"
            ,,,

For creating variables dynamically, at first you should make a loop为了动态创建变量,首先你应该做一个循环

    foreach ($first_arrays as $first_array)
    {
        foreach ($first_array as $key => $value) {
            $name = str_replace(" ","",$key);  //replace spaces
            ${$name} = $value;   //create PHP variable with your key
        }
    }

echo $foo; // will be fooValue
// here you have all variables that named by your array keys

In the end the solution was to walk through the array with foreach and just call the keys and assign them:最后,解决方案是使用 foreach 遍历数组,然后调用键并分配它们:

foreach ($csv as $value){

    $FirstName = $value["First"];
    $LastName = $value["Last"];
...
}

I was obviously making things harder as they were.我显然让事情变得更难了。 Thanks for the input anyway:)无论如何感谢您的输入:)

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

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