在试图吸引学生时,foreach没有工作

时间:2017-01-20 06:35:45

标签: php arrays foreach

echo "<pre>";  print_r($jobbrnchesids); exit;

<pre>Array
(
    [0] => Array
        (
           [id_branch] => 6
        )

    [1] => Array
        (
            [id_branch] => 1
        )
    )

从上面的数组中,我正在获得工作ID分支..现在我正在努力让那些拥有这些分支的学生。 我已经尝试过这种方式,但是出现了问题,无法调试,任何人都可以帮助我。

$studentBranch = '';
  foreach ($jobbrnchesids  as $k => $v){
      $stuBranch = $conn->query("SELECT student_pid FROM tbl_students
                    WHERE graduation_branch = ".$v." ");
       $studentsWithBranches[] = $stuBranch->fetch_assoc();
   }
echo "<pre>";  print_r($studentsWithBranches); exit;

4 个答案:

答案 0 :(得分:3)

缺少数组索引&#39; id_branch&#39;

尝试:

$stuBranch = $conn->query("SELECT student_pid FROM tbl_students
                WHERE graduation_branch = ".$v['id_branch']." ");

答案 1 :(得分:3)

而不是$v,它必须是$v['id_branch']

答案 2 :(得分:2)

通过执行以下操作来减少开销:

 $branchIds = array_column($jobbrnchesids,"id_branch");

 $result = $conn->query("SELECT student_pid FROM tbl_students
            WHERE graduation_branch IN (".implode(",",$branchIds.")");
 $studentsWithBranches = $result?$result->fetch_all(MYSQLI_ASSOC):[];

array_column返回输入数组

中单个列的值

答案 3 :(得分:2)

$studentBranch = '';
foreach ($jobbrnchesids as $k => $v) {
    $stuBranch = $conn->query("SELECT student_pid FROM tbl_students WHERE graduation_branch = '" . ['id_branch'] . "'");
    $studentsWithBranches[] = $stuBranch->fetch_assoc();
}
echo "<pre>";
print_r($studentsWithBranches);
exit;