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:
Post1
Post2
Post3
Post5
Post4
As needed:
Post1
Post2
Post3
Post4
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.