我有两个阵列:
已通过表单填充的$ teachArray。
$ learnArray是PDO Select查询的结果。
我想使用array_diff()函数将$ teachArray与$ learnArray进行比较,以便将新数据插入到我的数据库中。
我不知道如何正确地将$ learnArray转换为与$ teachArray相同的格式。
当我print_r($ teachArray)时,我得到结果:数组([0] => 1 [1] => 2)
当我print_r($ learnArray)时,我得到结果:Array([0] => Array([language_id] => 1)[1] =>数组([language_id] => 2))
if(isset($_POST['teach']))
{
$teachArray = $_POST['teach'];
$sqlGet = "SELECT language_id FROM language_skill WHERE person_id = :person_id AND language_learning = :language_learning";
$query = $handler->prepare($sqlGet);
$query->bindValue(':person_id', $_SESSION['person_id']);
$query->bindValue(':language_learning', 1);
$query->execute();
$number_of_rows = $query->rowCount();
$learnArray = $query->fetchAll(PDO::FETCH_ASSOC); **// How do I correctly fetch it.**
$sqlInsertTeach = "INSERT INTO language_skill (person_id, language_id, language_learning, language_teaching)
VALUES(:person_id, :language_id, :language_learning, :language_teaching)";
if ($number_of_rows > 0) {
$differentLanguageChosen = array_diff($teachArray, $learnArray);
foreach ($differentLanguageChosen as $dataTeach) {
$query = $handler->prepare($sqlInsertTeach);
$query->bindValue(':person_id', $_SESSION['person_id']);
$query->bindValue(':language_id', $dataTeach);
$query->bindValue(':language_learning', 0);
$query->bindValue(':language_teaching', 1);
$query->execute();
}
}
}
答案 0 :(得分:1)
替换
$learnArray = $query->fetchAll(PDO::FETCH_ASSOC);
与
$learnArray = [];
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$learnArray[] = $row['language_id'];
}
甚至更简单:
$learnArray = $query->fetchAll(PDO::FETCH_COLUMN, 0);
其中0
是您要获取的列的索引。由于您只有language_id
列 - 它的索引是0。