有人可以用评论解释/注释这个Ruby片段吗?

时间:2010-05-12 14:17:00

标签: ruby

请解释这个Ruby代码,以便我可以将其转换为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

3 个答案:

答案 0 :(得分:6)

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

很抱歉将C与伪代码混合,但我希望它有所帮助!

答案 1 :(得分:1)

第一位就像这样形成一个数组:

$data[2009][17] = 10;

PHP相当于:

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

第二部分将等同于以下内容:

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

希望有所帮助:)

答案 2 :(得分:0)

$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]}";
    }
}

请注意,year_low和year_high是当前代码段中未定义的变量,但您应该知道它们。

另外,$ mysql_results应该是一个包含数据库返回的所有行的数组。

简而言之,以下代码执行此操作:

  • 制作一个每年分组的数组,然后每周分组,其中包含值'count'
  • 循环显示此数组,按顺序显示年份,星期和'count'的值,如果有的话