gpt4 book ai didi

php - PDO 比较两个不同格式的数组

转载 作者:行者123 更新时间:2023-11-29 10:51:11 25 4
gpt4 key购买 nike

我有两个数组:
$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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com