简体   繁体   中英

foreach not looping all data

my first query that gets all rows that contain both the user who requested friendship ( authenticated user id ) and inbound friendship ( inbound user id ). This works if I echo $rowsget, it echos the correct rows, the problem I'm having is that it will only loop through up to two usernames, once I take away the ability for it to loop through the profiles own username it will only loop through one row then stop, I have tried what some people have said to do but it now says this error message when I try to load the profile page, "Object of class Illuminate\\Support\\Collection could not be converted to int" Here is the code, any help is appreciated, I have been stuck on this for hours now.

Query

$rowsget = DB::table('friends')->where(function(Builder $query) use($uid) {
    $query->where('requesteeid', $uid)
        ->orWhere('inboundid', $uid);
})
->where('approved', true)
->get();

$rowfetchfriend = [];
if(count($rowsget) > 0){
    foreach($rowsget as $get) {
        $getrequestee = $get->requesteeid;
        $getinbound = $get->inboundid;
        $rowfetchfriend += DB::table('users')->where('id', $getrequestee)- 
>orWhere('id', $getinbound)->get(['id', 'avatar', 'username']);
}

Loop through usernames

foreach($rowfetchfriend as $loop) {
        if($loop->id != $uid) { //make sure own user isnt displayed
            echo $loop->username; // echo all usernames that are
        }
    }
}

Use this method (or the push() method) when adding to an array:

Instead of this:

$rowfetchfriend += DB::table('users')->where('id', $getrequestee)->orWhere('id', $getinbound)->get(['id', 'avatar', 'username']);

Try this:

$rowfetchfriend[] = DB::table('users')->where('id', $getrequestee)->get(['id', 'avatar', 'username']);
$rowfetchfriend[] = DB::table('users')->where('id', $getinbound)->get(['id', 'avatar', 'username']);

The class and its methods are listed here: https://laravel.com/api/5.5/Illuminate/Support/Collection.html#method_count

You can use "push" method of laravel collection.

try this :

$rowfetchfriend = [];
    if(count($rowsget) > 0) {
        foreach($rowsget as $get) {
            $getrequestee = $get->requesteeid;
            $getinbound = $get->inboundid;
            $temp = DB::table('users')->where('id', $getrequestee)->orWhere('id', $getinbound)->get(['id', 'avatar', 'username']);
            array_push($rowfetchfriend, $temp->toArray());
        }
    }

and Loop through usernames :

for ($i=0; $i < count($rowfetchfriend); $i++) {
        if($rowfetchfriend[$i][0]->id != $uid) { //make sure own user isnt displayed
            echo $rowfetchfriend[$i][0]->username; // echo all usernames that are
        }
    }

I tested it and work correctly.

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