我已经厌倦了找出为什么代码不是foreach的循环。第一个循环是从数据库中获取人名,我像往常一样使用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]}]
请指给我出去,因为我被困在这里好几个小时了。问候, 您正在寻找的解决方案:
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)
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'");
或
$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
不要忘记关联数组键中的引号