doupai8095 2018-05-12 04:41
浏览 124
已采纳

如何将查询结果插入到php中的数组并在另一个数组中检查它们

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 lawyerBades.how to do it.

Here is my code up to now.

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

        }


    }
  • 写回答

1条回答 默认 最新

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

    Update

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?