简体   繁体   中英

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 . Then we sort $ch2_response using usort - we compare book names with strcmp . Then you loop through all books and check if current book $ab['name'] exists in $userBooks array. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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