r/PHPhelp • u/Valuable_Spell6769 • Jul 10 '25
how to get all values outside foreach loop
i need to get all the values outside of a foreach loop in an array format i need all results
here is my code
public function all_invoices_details(){
$sql = "SELECT * FROM invoice_order CROSS JOIN invoice_order_item WHERE invoice_order.id=invoice_order_item.invoice_id ORDER BY invoice_no DESC";
$all_results = $this->_db->query($sql);
return $all_results;
}
<?php
if($this->all_invoices_details()->count() > 0){
foreach($this->all_invoices_details()->results() as $row){
$table_data = json_encode($row);
}
}
?>if i echo $table_data inside the foreach loop i get all results but outside of the loop i only get the first array item
2
Upvotes
3
u/99thLuftballon Jul 10 '25
Maybe I'm being dumb here, but why are you doing a cross join? Isn't this a case for an inner join?
3
u/colshrapnel Jul 10 '25
Are you sure? By the look of it, it must be the last one
2
u/eurosat7 Jul 10 '25
Uhm. You know that there is a limit on memory?
Lookup generators / yield. Or add pagination and limit the dataset.
2
u/Late-System-5917 Jul 10 '25
Every time the loop runs, you’re overwriting $table_data with the new row results. Try this:
echo json_encode($this->all_invoices_details()->results());
2
u/Big_Tadpole7174 Jul 10 '25
The problem is that you're overwriting
$table_dataon each iteration of the loop. Currently,$table_datawill contain only the last item from your results (not the first). To get all results in an array format, you can collect them in an array:Side note: You're calling all_invoices_details() twice in your current code. Consider storing the result in a variable to avoid running the query multiple times.
1
u/jalx98 Jul 10 '25
Are you doing an inline script?
1
u/custerdome427 Jul 11 '25
Doesn't json_encode take an array? Just json_encode($results)