dqq9695 2014-04-09 17:34
浏览 80
已采纳

PHP比较2个数组数组

Hi All I have 2 arrays for example in PHP as seen below:

[users] => Array ( [0] => Array ( [username] => Timothy ) [1] => Array ( [username] => Frederic ) ) 

[users2] => Array ( [0] => Array ( [username] => Johnathon ) [1] => Array ( [username] => Frederic ) [] => Array ( [username] => Peter))

I am trying to compare the contents of each array against each other in order to put a html element, I tried using a nested foreach as seen below:

foreach($users as $user){
    foreach ($users2 as $user2){
        if($user['username'] == $user2['username']){
            echo "<option value=' ".$user['username']."' selected = 'selected'>".$user['username']."</option>";
            break;
        } else{
            echo "<option value=' ".$user['username']."'>".$user['username']."</option>";
        }
    }
}

my issue is that the items are being echoed more than once which is ruining my select element. Any ideas on how to compare the contents of each?

I want to achieve a list of each name eg:

-Timothy
-Frederic (this should be highlighted as it is in both arrays)
-Johnathon
- Peter
  • 写回答

2条回答 默认 最新

  • doucheng1063 2014-04-10 08:52
    关注

    I would take it in a different way.

    //Create user array one
    $users = array();
    $users[] = array('username'=>'Timothy');
    $users[] = array('username'=>'Frederic');
    
    //create user array 2
    $users2 = array();
    $users2[] = array('username'=>'Johnathon');
    $users2[] = array('username'=>'Frederic');
    $users2[] = array('username'=>'Peter');
    
    $temp_array = array();
    
    foreach($users as $key => $value) {
        $temp_array[$value['username']] = '';
    }
    
    foreach($users2 as $key => $value) {
        $temp_array[$value['username']] = array_key_exists($value['username'], $temp_array) ? 'DUPLICATE' : null;
    }
    
    echo '<select>';
    foreach($temp_array as $key_value => $status) {
        echo "<option value='{$key_value}' ".(($status == 'DUPLICATE') ? 'selected style="background-color: yellow;"' : '').">{$key_value}</option>";
    }
    echo '</select>';
    

    I'll let the array take care of it self, if it shares the same key, it will merge, then just flag it with "duplicate".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行