'How can an associative multidimensional (multiple dimensions) PHP array get converted to downloadable CSV?
I have an associative multidimensional (dynamic length of dimensions) array. It originally comes from JSON data, but I understand that just makes things harder so I convert it using json_decode($original_data, true).
I'm interested to convert it to a clickable CSV file like echo '<a href="data:application/csv, ' . $data . '">Click to download</a>'.
I've tried many code variations, one of which I found online in https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php because its whole purpose is to "convert a multi-dimensional, associative array to CSV data". Alas, its code doesn't seem to be recursive. Unlike other functions I've tried it doesn't call itself recursively if the data isn't is_array.
Your assistance is appreciated.
Sample data:
$array = array(
'name' => 'Test',
'average' => 1,
'fp' => '',
'dates' => array(
'isScheduled' => '',
'startDate' => 1587418137,
'endDate' => 1587418137,
'pViewValue' => array(
'startDate' => '2020-04-20T18:28:57.000Z',
'endDate' => '2020-04-20T18:28:57.000Z',
)
)
);
echo '<pre>' . print_r($array, true) . '</pre>';
Array
(
[name] => Test
[average] => 1
[fp] =>
[dates] => Array
(
[isScheduled] =>
[startDate] => 1587418137
[endDate] => 1587418137
[pViewValue] => Array
(
[startDate] => 2020-04-20T18:28:57.000Z
[endDate] => 2020-04-20T18:28:57.000Z
)
)
)
Expected output:
name average fp dates-isScheduled date-StartDate date-endDate date-pViewValue-startDate date-pViewValue-endDate
test 1 1587418137 1587418137 2020-04-20T18:28:57.000Z 2020-04-20T18:28:57.000Z
Solution 1:[1]
Solution 2:[2]
CSV is table-like: columns in rows, seperated by a seperator.
They are unsuitable to use for dynamic length and depth datastructures.
So the short answer is: No, don't.
However, if you happen to have some knowledge about WHAT to expect, you could predefine the 'meaning' of each column and map that to certain places inside your CSV structure. But that is trickery, and only works if you know what goes where.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nelson Rakson |
| Solution 2 |
