I'm trying to get a multidimensional array into a csv file. data in the array is as such:
Array
(
[0] => Array
(
[product_id] => 1111
[name] => Alcatel One Touch Idol 2
[keyword] => alcatel-one-touch-idol-2
[options] => Array
(
[0] => Array
(
[price] => 54.0000
)
[1] => Array
(
[price] => 42.0000
)
[2] => Array
(
[price] => 10.0000
)
[3] => Array
(
[price] =>
)
[4] => Array
(
[price] =>
)
[5] => Array
(
[price] =>
)
[6] => Array
(
[price] =>
)
[7] => Array
(
[price] =>
)
[8] => Array
(
[price] =>
)
[9] => Array
(
[price] =>
)
)
)
[1] => Array
(...... etc)
I get all of the top level data, but then once it reaches the options array, i get Array to string conversion
errors. So i have two issue, i firstly need to see why i am getting this error, and then i need to fputcsv all of this information on one line per product.
So far i have this to parse the array into a csv:
$output = fopen("php://output",'w') or die("Can't open php://output");
header("Content-Type:application/csv");
header("Content- Disposition:attachment;filename=product_catalog.csv");
$first_line = explode(",", $first_line);
fputcsv($output, $first_line);
foreach($csv as $file) {
fputcsv($output, $file);
}
fclose($output) or die("Can't close php://output");
If anyone could help me i'd really appreciate that. regards.
To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file.
You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.
The fputcsv() function in PHP is an inbuilt function which is used to format a line as CSV(comma separated values) file and writes it to an open file.
I would suggest to flatten each array first:
foreach ($csv as $file) {
$result = [];
array_walk_recursive($file, function($item) use (&$result) {
$result[] = $item;
});
fputcsv($output, $result);
}
In each iteration it would create an array like this:
[1111, 'Alcatel One Touch Idol 2', 'alcatel-one-touch-idol-2', 54, 42, ...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With