Skip to content
Advertisement

How to exclude identical elements from the foreach?

Tell me pls, how to exclude identical elements from the foreach?

Code:

$sql = 'SELECT * FROM users, posts 
    WHERE posts.author_id = users.id';
$rows = R::getAll($sql);
$data = R::convertToBeans('posts',$rows);

foreach ($data as $element) {
    echo $element->login . '<br/>' . $element->name . '<br/><br/>';
}

Result:

mail_1@test.com

Post1

mail_1@test.com

Post2

mail_2@test.com

Post3

mail_3@test.com

Post5

mail_2@test.com

Post4

As needed:

mail_1@test.com

Post1

Post2

mail_2@test.com

Post3

Post4

mail_3@test.com

Post5

Advertisement

Answer

Without knowing all details, this approach might not work in all cases (but it works on this one):

usort($data, function($a, $b) { return strcmp($a->login, $b->login); });

foreach ($data as $i => $element) {
    if ($i === 0 || $data[$i-1]->login !== $element->login) {
        echo $element->login . '<br/><br/>';
    }

    echo $element->name . '<br/><br/>';
}

What this does is it sorts by login field in ascending order and then iterating through sorted array. If the previous element’s login field is different than current’s, then it means we have a new login value.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement