August 15, 2010 0

PHP buckets

By admin in TechDates

So I’ve been held back this week (mostly work stuff), but I wanted to address a technique that my was introduced to me by a neighbor at work. Essentially I had an object of array information, and had to group them together by date before outputting them visually.

I had heard a couple things around the office about ‘buckets’ and decided to ask. So here’s the code in whole:

$buckets = array();
foreach ($data as $row) {
     $dateVariable = substr($row['meta_when'], 0, 10);
     $tempBucket = $buckets[$dateVariable];
     if (empty($tempBucket)) {
          $tempBucket = array();
     }
     $tempBucket[] = $row;
     $buckets[$dateVariable] = $tempBucket;

And here’s a step by step breakdown

$buckets = array();

This is the array that will hold the information. The key of each array element will hold the common denominator (in this case, the date). From here, I start up my foreach loop for the variable $data.

$dateVariable = substr($row['meta_when'], 0, 10);

The ‘meta_when’ key holds a datetime in the format YYYY-MM-DD 00:00:00, and I only want to categorize by date, not time. This line returns the date without the time to my variable, which will become a key for the $buckets array.

$tempBucket = $buckets[$dateVariable];
if (empty($tempBucket)) {
        $tempBucket = array();
}

These lines are pretty interesting, and were an initial source of confusion. $tempBucket receives whatever is in the bucket array for the key that was derived in the previous line. If that array is empty, then it gets initialized as a new array. Otherwise, $tempBucket remains in stasis.

$tempBucket[] = $row;

Here, the current data is being pushed onto the $tempBucket array. If the array hadn’t existed previously, this will be the first element on the array we created in the previous if/then statement. Otherwise, it will be added on to the end of the array.

$buckets[$dateVariable] = $tempBucket;

Re-assignment: the array with the updated information overwrites the array derived in the earlier part of the code.

It’s actually pretty simple in concept, but it would have taken me a long time to figure out on my own.

Leave a Reply