So, I'm trying to display an associative array generated from a table in my database. These are the steps I'm trying to accomplish:
- Get result set from database that's already sorted in certain order based on a column(Ascending/Descending).
- Add/Transfer/Append each record/row in the result set to another array. While in the process of appending, check if the array we are adding records has a value(based on a different column) similar to the record we are currently adding.
- If the value we are checking for is already there, skip appending. If not, append the record and continue with the loop until the end of the result set.
This is the sample data I am working with, tbl_user_details: Sample data
As you can see, it has been sorted in descending order based on the user_pos column. If you look at the user_id column, we have duplicate values. What I am trying to achieve is adding each record to an array and skipping the duplicate values based on the user_id column.user_id = 4 and user_pos = 7. Next will be ada with user_id = 2 and user_pos = 6. The next record which we are not going add is woz with user_id = 2 and user_pos = 5 because we already have someone with user_id = 2. So, we skip to adding ghopper who has user_id = 3 and user_pos = 4... and so forth. I think this example explains the flow of data I need displayed.
I've tried some simple code to get this done which it's clearly not working. Here is the snippet:
$query3 = "SELECT * FROM `user_details` ORDER BY `user_details`.`user_pos` DESC";
$user_set = mysqli_query($connection, $query3);
if (!$user_set) {
die("Database query failed.".mysqli_error($connection));
}
$user_arr = array();
while ($row = mysqli_fetch_assoc($user_set)) {
if (in_array($row["user_id"], $user_arr)) {
continue; // skip if we already have this value in array
}
$user_arr[] = $row;
}
The records that should be displayed are of aswartz, ada, ghopper and rasmusl. The rest are ignored. When I display the data in '$user_arr[]' using the foreach loop method, it still displays the whole data as it is on the table.