当另一个foreach在里面时,Php不是循环

时间:2014-07-05 07:23:57

标签: php loops foreach

我已经厌倦了找到为什么代码不是循环使用foreach。第一个循环是从db中获取人名,我像往常一样使用while循环,它可以工作。第二个循环我测试了他们每个人在一个月内做的总动作,所以我每个月使用一个foreach循环。但问题出在这里。由于没有任何线索,我无法再次循环。

这是我的代码:

error_reporting(E_ALL);
$thisYear=intval(date("Y"));

for($i=1;$i<13;$i++){
    $i=sprintf("%02d",$i);
    $monArr[]=$i;
}

//select all team members    
$sql_sTeam=mysqli_query($con,"select * from TEAMNAMES order by fname asc");
$result=array();    
while($rec_sTeam=mysqli_fetch_array($sql_sTeam)){       
    $rows['name']=$rec_sTeam['sale_fname'];//sale name

    foreach($monArr as $key=>$val){
        //$rows['data'][]=(int)$key;
        $mon=intval($val);
        //n action each member\
        $sql_mLog=mysqli_query($con,"select * from mail_log where mlog_sid='$rec_sTeam[imap_sid]' and year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");
        $num_mLog=mysqli_num_rows($sql_mLog);
        $rows['data'][] =(int)$num_mLog;//(int) will remove double qoutes around numbers        
    }//foreach

    array_push($result,$rows);
}//while
echo json_encode($result);

TEAMNAMES中有4个人,但这是json_encode的唯一结果:

[{"name":"Ar-eshah","data":[0,0,0,0,0,0,6,0,0,0,0,0]}]

请指出我离开这里因为我被困了几个小时。 的问候,

2 个答案:

答案 0 :(得分:1)

这是您正在寻找的解决方案:

error_reporting(E_ALL);
$thisYear = intval(date("Y"));

for($i = 1; $i < 13; $i++){
    $i = sprintf("%02d",$i);
    $monArr[] = $i;
}

//select all team members    
$sql_sTeam = mysqli_query($con,"select * from TEAMNAMES order by fname asc");
$result=array();    
while($rec_sTeam=mysqli_fetch_array($sql_sTeam)){
    $row = array();     
    $row['name']=$rec_sTeam['sale_fname'];//sale name
    $row['data'] = array();

    foreach($monArr as $key=>$val){

        $mon=intval($val);
        //n action each member\
        $sql_mLog=mysqli_query($con,"select * from mail_log where mlog_sid='$rec_sTeam[imap_sid]' and year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");
        $num_mLog=mysqli_num_rows($sql_mLog);
        $row['data'][] =(int)$num_mLog;//(int) will remove double qoutes around numbers        
    }//foreach

    $result[] = $row;
}//while
echo json_encode($result)

答案 1 :(得分:0)

任何MySQL错误?在这一行:

    $sql_mLog=mysqli_query($con,"select * from mail_log 
where mlog_sid='$rec_sTeam[imap_sid]' and 
year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");

您需要制动字符串以添加数组值或使用花括号......如下所示:

    $sql_mLog=mysqli_query($con,"select * from mail_log 
where mlog_sid='".$rec_sTeam[imap_sid]."' and 
year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");

OR

    $sql_mLog=mysqli_query($con,"select * from mail_log 
where mlog_sid='{$rec_sTeam[imap_sid]}' and 
year(mlog_dtime)='{$thisYear}' and month(mlog_dtime)='{$mon}' ");

一个例子:

    $a = array("name"=>"predte4a");
echo "My name is: $a['name']";
// will echo My name is array()['name']
echo "My name is: {$a['name']}";
//will echo My name is predte4a

不要忘记关联数组键中的引号