Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Filling in missing hours from array 1

Status
Not open for further replies.

JamesGMills

Programmer
Aug 15, 2005
157
GB
Hi,

I have the follow array returned from my database query.


Array
(
[0] => Array
(
[Hour] => 1
[Hits] => 8
)

[1] => Array
(
[Hour] => 8
[Hits] => 11
)

[2] => Array
(
[Hour] => 9
[Hits] => 6
)

[3] => Array
(
[Hour] => 10
[Hits] => 14
)


I need to end up with an array looking something like this

Array
(
[1] => 8
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 0
[7] => 0
[8] => 11
...

Any ideas?


------------------------
 
The first thing would be to turn your Array, into the format of your expected result.

Code:
<?PHP
$newarray="";

foreach($myarray as $subarray){
$newarray[$subarray['Hour']]=$subarray['Hits'];
}

This should produce an array looking like this:

Array
(
[1] => 8
[8] => 11
[9] => 6
[10] => 14
)

From there it should be easy to fill in the gaps. Just stepping through the array, and looking for the missing keys using isset(). You would have to store the highest hour from the previous run through the array to use as a base.

Code:
$max=$subarray['Hour'];
for($i=1;$i<=$max;$i++){
if(!isset($newarray[$i])){
$newarray[$i]=0;
}

}
?>

That should fill in the missing gaps. The last bit would be to sort it by Key, but its not completely necessary.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Hi,

Great reply. Thaks for detail and explination... When looking at these things it looks so easy... so much of programming is not just knowing the functions but being able to visulise the data and understand how to use what function the right way to get the data your after...

Thanks

------------------------
 
When I have a finite set of data for an array, I'll initialize the array and create it beforehand.

Code:
$newarray = array();
for($i=0;$i<=23;$i++){
     $newarray[$i] = 0;
}

Then just fill in the blanks as needed with the loop from the query.

Code:
loop start
     $newarray[$hour] = $hits;
loop end

I'm not sure if it's any more efficient that way, but when I can avoid an IF statement, I think it can help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top