Skip to content
Advertisement

Need two dimensional array for 2 column CSV from 2 strings

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)

JavaScript

I need this array pattern like this

JavaScript

I will then use the below code to generate 2 column CSV via PHP

JavaScript

Advertisement

Answer

Since the values are comma separated strings, explode them into arrays:

JavaScript

Then you can just use the key to match up the values from each array (assuming that they are the same length):

JavaScript

Or combine them:

JavaScript

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:”

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement