简体   繁体   English

嵌套的foreach循环中的匹配结果-PHP

[英]Matched results in nested foreach loop - PHP

I am querying two sets of data the first contains a full list of address books, the second contains only those that a user is subscribed to. 我要查询两组数据,第一组包含通讯簿的完整列表,第二组仅包含用户已预订的那些。 I want to present the full list and just highlight the ones the user's subscribed to. 我想显示完整列表,仅突出显示用户已订阅的列表。 My code so far returns the full list of address books as well as the users address books (in red) but displays duplicates. 到目前为止,我的代码返回通讯录的完整列表以及用户通讯录(红色),但显示重复项。 Can anyone help remove the duplicates? 任何人都可以帮助删除重复项吗?

<?php 

    foreach($ch2_response as $ub){
            if($ub['visibility'] == 'Public' ){
                echo $ub['name'] . '<br>';
            }
        foreach($ch1_response as $ab){
           if($ab['visibility'] == 'Public' && $ab['name'] == $ub['name'] ){
                echo '<p style="color:red;">' . $ab['name'] . '</p>';

            }
        }
    }

    ?>

The code would go something like this (included example values) 该代码将是这样的(包括示例值)

<?php

$ch1_response = [
    ["name" => "Book 1", "visibility" => "Public"],
];

$ch2_response = [
    ["name" => "Book 1", "visibility" => "Public"],
    ["name" => "Book 2", "visibility" => "Public"],
    ["name" => "Book 3", "visibility" => "Private"],
];

$userBooks = [];

foreach ($ch1_response as $ub) {
    if ($ub['visibility'] == "Public") {
        $userBooks[] = $ub['name'];
    }
}

usort($ch2_response, function ($a, $b) {
    return (strcmp($a['name'], $b['name']));
});

foreach ($ch2_response as $ab) {
    if ($ab['visibility'] == "Public") {
        if (in_array($ab['name'], $userBooks)) {
            echo '<p style="color:red;">' . $ab['name'] . '</p>';
        } else {
            echo '<p>' . $ab['name'] . '</p>';
        }
    }
}

?>

First you save all user books names that are Public in one array $userBooks . 首先,将所有公共用户书籍名称保存在一个数组$userBooks Then we sort $ch2_response using usort - we compare book names with strcmp . 然后,我们使用usort$ch2_response进行排序-我们将书名与strcmp进行比较。 Then you loop through all books and check if current book $ab['name'] exists in $userBooks array. 然后,您遍历所有书籍并检查$userBooks数组中是否存在当前书籍$ab['name'] If yes, echo book name in color red, otherwise, just echo it without color. 如果是,请以红色显示书名,否则,请以无颜色显示它。

You can first compare both the arrays and get the unique values in new array and print values using that new array. 您可以先比较两个数组,然后获取新数组中的唯一值,然后使用该新数组打印值。

$new_array = array_unique( array_merge($ch2_response, $ch1_response) );

print_r($new_array);

I hope this will help you! 我希望这能帮到您!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM