Combining multiple arrays into one array

I have this piece of code from which I want to get a single array containing all the values.

$sql = "SELECT * FROM interest where interest='".$interest."' and userid!='".$myuserid."'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $userid = $row["userid"]; if($searchtype == 'both') { $sql2 = "SELECT * FROM register where id='".$userid."' and discover = 'on' and id!='".$myuserid."'"; $result2 = mysqli_query($conn, $sql2); if (mysqli_num_rows($result2) > 0) { while($row2 = mysqli_fetch_assoc($result2)) { echo "<pre>"; print_r($row2); echo "</pre>"; } } } } } 

The o / r that I get is something like this

 Array ( [id] => 1 [email] => A1 [username] =>B1 [password] => C1 [gender] => C1 ) Array ( [id] => 2 [email] => A2 [username] => B2 [password] => C2 [gender] => D2 ) Array ( [id] => 3 [email] => A3 [username] => B3 [password] => C3 [gender] => D3 ) 

But I want to get all the data in one array like this

 Array ( [0] => Array ( [id] => 1 [email] => A1 [username] =>B1 [password] => C1 [gender] => C1 ) [1] => Array ( [id] => 2 [email] => A2 [username] => B2 [password] => C2 [gender] => D2 ) [2] => Array ( [id] => 3 [email] => A3 [username] => B3 [password] => C3 [gender] => D3 ) } 

can anyone tell how i can do this

+5
source share
3 answers

Take one array variable before the start of the loop, as $user_data = array(); , and in the inner loop you should set $user_data[] = $row2;

 if (mysqli_num_rows($result) > 0) { $user_data = array(); while($row = mysqli_fetch_assoc($result)) { $userid = $row["userid"]; if($searchtype == 'both') { $sql2 = "SELECT * FROM register where id='".$userid."' and discover = 'on' and id!='".$myuserid."'"; $result2 = mysqli_query($conn, $sql2); if (mysqli_num_rows($result2) > 0) { while($row2 = mysqli_fetch_assoc($result2)) { $user_data[] = $row2; } } } } print_r($user_data); //Print here your user_data outside the loop. } 
0
source

Create an array variable as $a=array(); at the beginning of your code

Get the value of the string in the array $ a [] = the value of your string (while loop), then print this outer loop, you get the whole value in a single array, for example

 print_r($a); 
+1
source

You are almost close to your goal, you just need to define one array and store the data of each row in it

 // array which contains all rows data $all_rows = array(); // <------ step 1 if(mysqli_num_rows($result2)) { while($row2 = mysqli_fetch_assoc($result2)) { // every record data is stored here $all_rows[] = $row2; // <------ step 2 } } if(!empty($all_rows)) { print_r($all_rows); }else { echo "do some thing else since zero records fetched"; } 
0
source

All Articles