Reputation: 147
I'm relatively new to PHP, so please excuse my ignorance if this is an easy one.
I am pulling in results from an API call with an end goal being that I write all results to a CSV file, I was able to get everything working, except for the fact that it only writes the first array to the CSV file. I know there are more records (arrays) because when I echo the results I typically get 10-15 results back. Below is my code that I'm using.
foreach ($list as $order) {
$listOrders = array (
array($order->getBuyerName(), $address['AddressLine1'], $address['AddressLine2'], $address['AddressLine3'], $address['City'], $address['StateOrRegion'], $address['PostalCode'], $orderinfo->getSKU())
);
}
$fp = fopen('order-file.csv', 'w');
foreach ($listOrders as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Here is a sample of the one result, though there should be around 10-15:
"TONYA","7X XX Avenue",,,"Spokane Valley",WA,99212,B123
Upvotes: 1
Views: 45
Reputation: 278
You always overwrite the $listOrders
array with each foreach
cycle. To add element to array, use $listOrders[] = $var
syntax, so it should look something like this
$listOrders = array();
foreach ($list as $order) {
$listOrders[] = array($order->getBuyerName(), $address['AddressLine1'], $address['AddressLine2'], $address['AddressLine3'], $address['City'], $address['StateOrRegion'], $address['PostalCode'], $orderinfo->getSKU());
}
Upvotes: 2