1

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
3
  • 1
    Your'e only creating a $listOrders array with one entry: foreach ($list as $order) { $listOrders[] = array($order->getBuyerName(), $address['AddressLine1'], $address['AddressLine2'], $address['AddressLine3'], $address['City'], $address['StateOrRegion'], $address['PostalCode'], $orderinfo->getSKU()); } Commented Sep 19, 2016 at 19:43
  • 1
    You're overwriting $listOrders on each iteration. Define it as an array before your foreach, then use what Mark said to add a new array on each loop. Commented Sep 19, 2016 at 19:43
  • Thanks guys, makes sense, your help along with Jan below fixed the issue. Commented Sep 19, 2016 at 19:53

1 Answer 1

2

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()); 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.