Pregunta

I have a data range that I need to pull results from a database. Usual problem, not every day has records, and its skewing my charts. I need to pad the results with 0s and have a question on the best way.

I have a php routine that populates an array with the correct number of days, and need to cycle through my mysql.recordset inserting the values if there is one into the array for that day in the loop, or leaving it as zero if not.

What is the best way to carry out the search/comparison without having to loop through the whole recordset to see if there is any data for the date I am processing in the loop.

Assuming theres 90 days, thats a loop through 90 records for each day (90*90 , 8100 compares which scares me)

There will never be more than 366 records in a dataset.

Using PHP latest versions.

¿Fue útil?

Solución

Create a 2D associative array, with the date being the first dimension. So you create an array $allrecords where the keys are '2012-01-01', etc., and the value of each of these is an associative array that mimics the other structure of your data, with zeroes throughout. So if your data looks like:

DATE        FIELDA   FIELDB   FIELDC
2012-01-01      10       20       30
2012-01-03       1        2        3

You create the array so that

$allrecords["2012-01-01"]["FIELDA"]=0;
$allrecords["2012-01-01"]["FIELDB"]=0;
$allrecords["2012-01-01"]["FIELDC"]=0;
$allrecords["2012-01-02"]["FIELDA"]=0;
etc.

You would loop through your dataset only once, doing somthing like

$allrecords["2012-01-01"]["FIELDA"]=10;
$allrecords["2010-01-01"]["FIELDB"]=20;
$allrecords["2010-01-01"]["FIELDC"]=30;
get next record
$allrecords["2010-01-03"]["FIELDA"]=1;
etc.

Then you loop through the array to do your output.

Or if you can change the query, you could create a temporary table of the dates you want and join it to the results and bring the data in with the gaps filled.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top