douna1895 2013-12-06 18:49
浏览 36
已采纳

试图比较两个数组中的值

I have a list of users on a webpage and am trying to compare each username with a list of users in an array. But for some reason the following code always returns false. Some usernames do match and should therefore display a yes next to the username.

foreach($result AS $user){
    foreach($listarray AS $name){
        if($user['username'] == $name){
            $whitelisted = 'Yes';
        } else {
            $whitelisted = 'No';
        }
    }
    echo '<tr><td><p>'.$user['username'].'</p></td><td><p>'.$user['location'].'</p></td><td><p>'.$user['date_joined'].'</p></td><td><p>'.$whitelisted.'</p></td>';
}

Why is this comparison returning false even when some names should match?

  • 写回答

5条回答 默认 最新

  • dongqiabei7682 2013-12-06 18:59
    关注

    You need to break the inner foreach loop if there is a matching element. Alternatively you can use the in_array function to check if there is value exists in an array

    foreach($result AS $user){
        $whitelisted = 'No';
        if (in_array($user['username'], $listarray ))
        {
           $whitelisted = 'Yes';
        }
        echo '<tr><td><p>'.$user['username'].'</p></td><td><p>'.$user['location'].'</p></td><td><p>'.$user['date_joined'].'</p></td><td><p>'.$whitelisted.'</p></td>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化