2018-05-12 04:41 阅读 103


I have lawyer , lawyerBadges, badges tables in mysql database.I want to load all the badge ids in badge to an array.(allBadges[]).And I want to load the all the badge ids of lawyer to another array(lawyerBadges[]).Then I want to check whether the allBadges elements are in to do it.

Here is my code up to now.

    $username = $_SESSION['username'];


    function getPoints(){
        global  $connection;
        global $username;
        $pointCount_query =mysqli_query( $connection,"SELECT * FROM lawyer WHERE username='".$username."'");
        $points= (int)$pointCount['points'];



    function addBadges($user_points){
        global  $connection;
        global $username;
        $badge_array = array();
        $badgeList=mysqli_query($connection,"SELECT bId FROM badge ");

        $lawyers_badges=mysqli_query($connection,"SELECT bID FROM lawyerbadge WHERE username='".$username."'");

        //this is the problem area
       foreach( $badge_array  as $value){
            echo $value.'<br />';


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duan1983 duan1983 2018-05-12 04:56

    You'll need 2 for loops. The outer loop will iterate over all the badges. The inner loop will iterate over all the lawyers badges. If outer loops badge is not found, it will echo the badge

    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 />';


    A better alternative would be to use LEFT JOIN, which will require no manual looping and get result with only one query.

    SELECT badge.bId FROM badge 
    LEFT JOIN lawyerbadge  ON badge.bId = lawyerbadge.bID
    WHERE username = '$username'"
    AND lawyerbadge.bID IS NULL;

    This will return only badges which you're interested in.

    点赞 评论 复制链接分享