Reputation: 115
I have got all the user records using random function from user table, Now when i loop the users and try to display,
I need the record like this:
user a = user b
user c = user a
user b = user c
I must not get this kind:
user a = user a
user b = user b
Below is my code
public function randomUser(){
$userData1 = User::inRandomOrder()->orderBy('email', 'ASC')->get();
$userData2 = User::inRandomOrder()->orderBy('id', 'DESC')->get();
foreach($userData1 as $key => $value ) {
if($userData1[$key]->id != $userData2[$key]->id){
echo $userData1[$key]->first_name.$userData1[$key]->last_name."-".$userData2[$key]->first_name.$userData2[$key]->last_name."<br>";
}
}
}
Upvotes: 1
Views: 108
Reputation: 725
inRandomOrder() is super slow so you might want not to use it. You should select your data once from DB with the help of simple query without orderBy.
Assign your resulted array of users in two variables.
$a = $b = ['user a','user b','user c'];
Shuffle array $a for random
shuffle($a);
Loop it in do-while loop Shuffle array $b and Compare both $a & $b arrays by index & values
do{
shuffle($b);
$c = array_diff_assoc($a, $b);
}while(count($c)!=count($a));
Assign your resulted array of users in two variables.
$a = $b = [array('id' => 1, 'name' => "abc"),array('id' => 2, 'name' => "def"),array('id' => 3, 'name' => "ghi")];
Shuffle array $a for random
shuffle($a);
Function to compare multidimensional arrays
function arrayRecursiveDiff($aArray1, $aArray2) {
$aReturn = array();
foreach ($aArray1 as $mKey => $mValue) {
if (array_key_exists($mKey, $aArray2)) {
if (is_array($mValue)) {
$aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
} else {
if ($mValue != $aArray2[$mKey]) {
$aReturn[$mKey] = $mValue;
}
}
} else {
$aReturn[$mKey] = $mValue;
}
}
return $aReturn;
}
Loop it in do-while loop Shuffle array $b and Compare both $a & $b arrays by index & values
do{
shuffle($b);
$c = arrayRecursiveDiff($a, $b);
}while(count($c)!=count($a));
Both arrays will be completely different from each other. Now you can do whatever with these two arrays.
Upvotes: 1
Reputation: 163938
You need to use some kind of algorithm here. For example, you could get all users into a collection. Then just get and remove each user from the collection using shift()
and/or pop()
methods. This is an example, modify it as you want:
$users1 = User::inRandomOrder()->get();
$users2 = $users1;
foreach ($users1 as $user) {
echo $user->full_name. ' - '. $users2->pop()->full-name;
}
Also, to make full_name
work, use an accessor instead of concatenating two string manually each time.
Upvotes: 0