简体   繁体   中英

Key/Value pair as variable in PHP

I'm have parsed a csv file into a associative array which looks like this:

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

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 ($csv as $value){

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

I was obviously making things harder as they were. Thanks for the input anyway:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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