我在 mysql 数据库中有律师、律师徽章、徽章表。我想将徽章中的所有徽章 ID 加载到一个数组中。(allBadges[])。我想将律师的所有徽章 ID 加载到另一个数组(lawyerBadges[]).然后我想检查allBadges元素是否在lawyerBades中。如何做。
这是我到目前为止的代码。
$username = $_SESSION['username'];
getPoints();
function getPoints(){
global $connection;
global $username;
$pointCount_query =mysqli_query( $connection,"SELECT * FROM lawyer WHERE username='".$username."'");
$pointCount=mysqli_fetch_array($pointCount_query);
$points= (int)$pointCount['points'];
addBadges($points);
}
function addBadges($user_points){
global $connection;
global $username;
$badge_array = array();
$badgeList=mysqli_query($connection,"SELECT bId FROM badge ");
$badges=mysqli_fetch_array($badgeList);
$lawyers_badges=mysqli_query($connection,"SELECT bID FROM lawyerbadge WHERE username='".$username."'");
while($row=mysqli_fetch_assoc($lawyers_badges)){
$badge_array[]=$row;
}
//this is the problem area
foreach( $badge_array as $value){
echo $value.'<br />';
}
}
最佳答案
您需要 2 个 for 循环。外循环将遍历所有徽章。内循环将遍历所有律师徽章。如果没有找到外循环徽章,它将回显徽章
foreach( $badgeList as $badge){
$badge_found_flag = false;
foreach( $badge_array as $lawyerBadge){
$badge_found_flag = true;
}
if($badge_found_flag == false){
echo $badge.'<br />';
}
}
更新
更好的替代方法是使用 LEFT JOIN
,它不需要手动循环并且只需要一个查询就可以得到结果。
SELECT badge.bId FROM badge
LEFT JOIN lawyerbadge ON badge.bId = lawyerbadge.bID
WHERE username = '$username'"
AND lawyerbadge.bID IS NULL;
这将只返回您感兴趣的徽章。
关于php - 如何将查询结果插入php中的数组并在另一个数组中检查它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50302911/