dongshuo9350 2017-01-06 19:42
浏览 380
已采纳

如何避免嵌套的foreach循环php中的重复

Why are values are getting printed multiple times (see images below). I need to print them only once.

<?php foreach($patchData3 as $tes3){?> 
    <?php foreach($patchData1 as $tes){?>
        <tr class="<?php if($tes->PATCH == $tes3->PATCH) {echo "red_color"; } ?>"> 
            <td><?php echo $tes->HOSTNAME;?></td>
            <td><?php echo $tes->VERSION;?></td> 
            <td><?php echo $tes->PATCH;?></td> <!--bgcolor="#FF0000"-->
        </tr>   
    <?php } ?>
<?php }?>

enter image description here
enter image description here

  • 写回答

1条回答 默认 最新

  • douzi7890 2017-01-06 20:13
    关注
    <?php foreach($patchData1 as $tes){ ?>          
        <tr class="<?php if(checkfunction($tes->PATCH,$patchData3) == TRUE) { echo "red_color"; } ?>"> 
            <td><?php echo $tes->HOSTNAME;?></td>
            <td><?php echo $tes->VERSION;?></td> 
            <td><?php echo $tes->PATCH;?></td> <!--bgcolor="#FF0000"-->
        </tr>   
    <?php } ?>
    
    <?php 
        function checkfunction($patch,$patchData3){
            foreach($patchData3 as $tes3){
                if($patch == $tes3->PATCH){
                    return true;
                }   
            }
        }
    ?>
    

    I used a function to overcome the duplication. Please comment if it does not work.

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

报告相同问题?