views:

84

answers:

4

Could someone please add comments to this code? Or, alternatively, what would be the pseudocode equivalent of this Ruby code?

It seems simple enough but I just don't know enough Ruby to convert this to PHP.

data = Hash.new({})
mysql_results.each { |r| data[r['year']][r['week']] = r['count'] }

(year_low..year_high).each do |year|
  (1..52).each do |week|
   puts "#{year} #{week} #{data[year][week]}"
  end
end

Any help whatsoever would be really appreciated.

Thanks!

+6  A: 
data = Hash.new({})
# create hash 'data'
mysql_results.each { |r| data[r['year']][r['week']] = r['count'] }
# maps each row from sql query to hash like this: data[2010][30] = 23
# So you can access 'count' from every year and week in very simple way

(year_low..year_high).each do |year|
# for (year = year_low; year <= year_high; year++) 
  (1..52).each do |week|
  # for (week = 1; week <=52; week++)
   puts "#{year} #{week} #{data[year][week]}"
   # printf("%d %d %d\n", year, week, data[year][week]);
  end
end

Sorry for mixing C with pseudo code, but I hope it helps!

klew
Second line in php does this: foreach($mysql_results as $row) { $data[$row['year']][$row['week']] = $row['count']; }
Kamil Szot
+1  A: 

The first bit is just forming an array like so:

$data[2009][17] = 10;

PHP equivalent of that would be:

foreach ($mysql_results as $r){
  $data[$r['year']][$r['week']] = $r['count'];
}

The second part would equate to the following:

foreach(range($year_low, $year_high) as $year){
  foreach(range(1, 52) as $week){
    print $year.' '.$week.' '.$data[$year][$week]
  }
}

Hope that helps :)

Throlkim
+1 for remembering the `range()` function. I always forget, and resort to a simple `for()` instead..
Duroth
A: 
$data = array();

#Build an array of 'count' per year/week
foreach($mysql_results as $r) {
    $data[$r['year']][$r['week']] = $r['count'];
}

#Loop through the $data variable, printing out the 'count' for each year in the array,
#and all 52 weeks that year
for($year = $year_min; $year <= $year_max; $year++) {
    for($week=1; $week<=52; $week++) {
        echo "$year $week {$data[$year][$week]}";
    }
}

Note that year_low and year_high are variables undefined in the current snippet, but they should be known to you.

Also, $mysql_results should be an array containing all rows returned by the database.

In short, the following code does this:

  • Make an array grouped per year, then per week, containing the value 'count'
  • Loop through this array, displaying, in order, the year, the week, and the value for 'count', if any
Duroth
A: 

Thanks guys -- With all of your responses I was able to get it working!!

Ronnie