【问题标题】:how to insert the query results to an array in php and check them in another array如何将查询结果插入php中的数组并在另一个数组中检查它们
【发布时间】:2018-05-12 13:07:37
【问题描述】:

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

        }


    }

【问题讨论】:

标签: php mysql mysqli


【解决方案1】:

您需要 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;

这将只返回您感兴趣的徽章。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    相关资源
    最近更新 更多