当前位置: 动力学知识库 > 问答 > 编程问答 >

mysql - PHP array created inside for loop but not printing

问题描述:

I created a script to get data from a mysql table for every year and put into array of respective year. I checked the sql and the while loop iteration is working.

<?php

mysql_select_db($database_hari,$hari);

$start=2013 ;

$end=2015;

$xdata=array();

for($year=$start;$year<=$end;$year++){

${"y".$year}=array();

$i=0;

$query=mysql_query("SELECT tld_master.location,tld_dose.year, AVG(tld_dose.dose)*4 as avgdose from tld_master left join tld_dose on tld_master.tldno=tld_dose.tldno where tld_master.site='F' and tld_dose.year=$year GROUP BY tld_dose.year, tld_dose.tldno");

while($result=mysql_fetch_array($query)){

$xdata[$i]=$result['location'];

${"y".$year."[".$i."]"}=$result['avgdose'];

$i++;

}

}

print_r($y2015);

?>

Print displays "Array()"

But if I am echoing each array value inside for loop it prints. Where is the mistake?

网友答案:
${"y".$year} = array()

creates a variable named $y2015, holding an array. The code

${"y".$year."[".$i."]"} = ...

creates an oddly named variable $y2015[0], which is completely unrelated to the variable $y2015. You want:

${"y".$year}[$i] = ...
网友答案:

Although there are ways to solve your problem with variable variables, I suggest you take different approach. What if year is a value you do not expect? It can easily lead to confusion. Instead you can use an array that you can iterate through without knowing the exact value of the year.

$yearArray = array();
for($year=$start;$year<=$end;$year++){
    $sql = "SELECT
              tld_master.location,tld_dose.year, AVG(tld_dose.dose)*4 as avgdose 
            FROM tld_master 
            LEFT JOIN tld_dose on tld_master.tldno=tld_dose.tldno 
            WHERE tld_master.site='F' and tld_dose.year={$year} 
            GROUP BY tld_dose.year, tld_dose.tldno";
    $query = mysql_query($sql);

    $yearArray[$year] = array();
    while($result=mysql_fetch_array($query)){
        $xdata[] = $result['location'];
        $yearArray[$year][] = $result['avgdose'];
    }
}

Now you can print the $yearArray variable to see your actual results. And you can use it easily.

print_r($yearArray["2015"]);
网友答案:

You override your array value with this statement ${"y".$year."[".$i."]"}=$result['avgdose']; Try to use this one instead: ${"y".$year."[".$i."]"}[]=$result['avgdose'];

分享给朋友:
您可能感兴趣的文章:
随机阅读: