PHP循环中允许的内存大小耗尽

I have the following code:

 15 $users = pg_fetch_all($result);
 16 $chart_data = array();
 17 foreach ($users as $value)
 18 {
 19         //var_dump($value);
 20         $temp = array();
 21         $temp['label'] = $value['id'];
 22         $temp['y'] = $value['sum'];
 23 print_r($temp);
 24 /*
 25 echo "<pre>";
 26         var_dump($temp);
 27 echo "</pre>";
 28 */      
 29         array_push($chart_data,$temp);
 30 }
 31 echo count($chart_data);

When I run my code, I get the following error message:

[Thu Apr 28 17:23:39.278844 2016] [:error] [pid 24321] [client 10.63.8.104:58362] PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) in /var/www/localhost/htdocs/audit/index.php on line 21

This is a sample of the output I get from the print_r():

Array ( [label] => 12 [y] => 0.0021 ) 

I can't see how line 21 is problematic here. Maybe I need to explicitly reset temp to an empty array?? Not sure too but any suggestions welcome. Thanks.

Ignoring the memory issues, it looks like you are just trying to change the associative array indexes from the column name to something else. Try doing it in the SELECT:

SELECT `id` AS label, `sum` AS y FROM `somewhere` . . .

Then your original $users = pg_fetch_all($result); should contain what you want.

It's fairly self-explanatory, isn't it? You perform an array_push into $chart_data, on each iteration, so $chart_data gets bigger on each iteration. Eventually, with your server settings as they and with your data as it is, you run out of memory before you get to the end.

Either handle less data or give yourself more memory. Your PHP settings are giving you 128MB, which is high but not insane. You can increase it if you are sure that you need to.

An alternative would be to revisit the need to create this huge array in the first place. You appear to be doing it only to rename the keys, which seems extremely wasteful. Consider renaming them in your database query so that they are what you want from the start. Then you can just iterate over the rows in sequence, and you don't have to read the entire dataset into memory all at once.

you can increase the allowed memory for all but I think this can be useful for you

<?php
ini_set('memory_limit', '1024M'); // write this line before your code