Skip to content

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:

[email protected]

Post1

[email protected]

Post2

[email protected]

Post3

[email protected]

Post5

[email protected]

Post4

As needed:

[email protected]

Post1

Post2

[email protected]

Post3

Post4

[email protected]

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