Home > Enterprise >  Retrieve an array of invoices instead of an object PHP
Retrieve an array of invoices instead of an object PHP

Time:04-09

I'm trying to retrieve a list of invoices per customer. So far I'm only retrieving the first object of the list. But how do I retrieve the whole list? I'm a beginner in PHP so I really can't figure this out and the docs of Chargebee aren't clarifying anything for me.

Here are the docs: https://apidocs.eu.chargebee.com/docs/api/invoices?prod_cat_ver=2&lang=php#list_invoices

And this is what I tried so far:

$customerID = $_POST['customerID']; 

require_once(dirname(__FILE__) . '/chargebee-php-2.8.3/lib/ChargeBee.php');

ChargeBee_Environment::configure("xxxx","xxxx");

$result = ChargeBee_Invoice::all(array(
  "limit" => 13,
  "sortBy[desc]" => "date",
  "customerId[is]" => (string)$customerID
  ));
  
foreach($result as $entry){
  $invoice = $entry->invoice();
}

$array = (array) $invoice;

echo json_encode($array);

Unfortunately I'm only retrieving the first item of the list. How do I get the whole list in an array, but encoded to a json string?

CodePudding user response:

You keep overwriting your $invoice variable.

Creating and empty array and pushing every invoice onto that should yield the result you want. So try this:

$customerID = $_POST['customerID']; 

require_once(dirname(__FILE__) . '/chargebee-php-2.8.3/lib/ChargeBee.php');

ChargeBee_Environment::configure("xxxx","xxxx");

$result = ChargeBee_Invoice::all(array(
  "limit" => 13,
  "sortBy[desc]" => "date",
  "customerId[is]" => (string)$customerID
  ));

$invoicesArr = [] // create empty array
  
foreach($result as $entry){
  array_push($invoicesArr, $entry->invoice()); // foreach invoice, push it to array
}

echo json_encode($invoicesArr);
  • Related