请解释这个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
答案 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应该是一个包含数据库返回的所有行的数组。
简而言之,以下代码执行此操作: