John Davidson

arrays - PHP: list() set variables dynamically form string (read any CSV file as formatted order)

0 comments
Message:


Can I set variables names as csv title (first line)?


I do think it, so I code this:


$string = "date, name, age"; // csv file title order format
$tit = explode(", ", $string); //array('date', 'name', 'age'); //will be called: $_date

//run php function to find a specific line
$arr = array('bash', 'monkey', 'badger'); //returned line
foreach ($tit as $i => $nam) {
$e = "_" . $nam;
$$e = $arr[$i];
}
//set variables contents as title name
echo $_name; //monkey

Works perfectly: Try it


But how to turn it into PHP function?


function toList ($tit,$arr) {
foreach ($tit as $i => $nam) {
$e = "_" . $nam;
$$e = $arr[$i];
}
}

$tit = array('date', 'name', 'age'); //will be called as: $_date
$arr = array('bash', 'monkey', 'badger');

toList($tit,$arr);

echo $_date;

As function, code breaks.


How should code it to Php function works?



My Answer:
"Name,Age,Location\nJohn,25,New York\nJane,30,Los Angeles";

// Convert string to array
$data = explode("\n", $string);

// Get the titles from the first line
$titles = explode(",", $data[0]);

// Remove the first line from the data array
unset($data[0]);

// Loop through the data array and set variables dynamically
foreach ($data as $row) {
$values = explode(",", $row);
$row_data = array_combine($titles, $values);

// Set variables dynamically
foreach ($row_data as $key => $value) {
$$key = $value;
}

// Now you can access the variables with the csv titles
echo "Name: $Name, Age: $Age, Location: $Location\n";
}

Rate this post

3 of 5 based on 3653 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us