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.

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题