I am working on a project to create 2 column CSV using PHP and i have the data stored as strings in 2 different variables . Consider below example of what i have and what i need further. Thank you in advance.
I have below 2 variables and data stored inside them. (data is separated by comma)
$title = title1,title2,title3,title4,title5..and so on
$values = value1,value2,value3,value4,value5..and so on
I need this array pattern like this
$multi_array = array
(
array(title1,value1),
array(title2,value2),
array(title3,value3),
);
I will then use the below code to generate 2 column CSV via PHP
// open the file "demosaved.csv" for writing
$file = fopen('demosaved.csv', 'w');
// save the column headers
fputcsv($file, array('Column 1', 'Column 2'));
// save each row of the data
foreach ($multi_array as $row)
{
fputcsv($file, $row);
}
// Close the file
fclose($file);
Advertisement
Answer
Since the values are comma separated strings, explode
them into arrays:
$title = explode(",", $title);
$values = explode(",", $values);
Then you can just use the key to match up the values from each array (assuming that they are the same length):
foreach ($values as $key => $val)
{
fputcsv($file, [$title[$key], $val]);
}
Or combine them:
$multi_array = array_combine($title, $value);
foreach ($multi_array as $title => $value)
{
fputcsv($file, [$title, $value]);
}
If you’re on an old version of PHP you’ll need array()
instead of [ ]
.
From the OP, since there many be duplicates in the string that would be duplicate keys: “use the below code to perform the same job and even keep the duplicate keys. PHP array_combine
removes the duplicate array entries but below code keeps all entries:”
$arrKeys = array('str', 'str', 'otherStr');
$arrVals = array('1.22', '1.99', '5.17');
function foo($key, $val) {
return array($key=>$val);
}
$arrResult = array_map('foo', $arrKeys, $arrVals);
print_r($arrResult);