我有两个数组:
已通过表单填充的$ teachArray。
$ learnArray是PDO Select查询的结果。
我想使用array_diff()函数将$ teachArray与$ learnArray进行比较,以便将新数据插入到我的数据库中。
我不知道如何正确地将$ learnArray转换为与$ teachArray相同的格式。
当我print_r($ teachArray)时,我得到的结果是:Array([0] => 1 [1] => 2)
当我print_r($ learnArray)时,得到以下结果:Array([0] => Array([language_id] => 1)[1] => Array([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();
}
}
}
最佳答案
更换
$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。关于php - PDO比较两个具有不同格式的阵列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43704485/