Dubstaphone
Dubstaphone

Reputation: 418

How can you put two arrays in the same order?

I'm pulling two arrays from my database. One of them is from the friends table, and the other is from the members table.

What I'm trying to do is display the usernames of the friends on the profile. That's done, but now I'm trying to make links to the person who has that username's profile (click on userName to go to userName's profile). The friends array ($friendsarr) has all of the ID's of the friends, and the username array ($friendunamearr) has the usernames that match the ID's. However, they are not in the same order.

If I forgot to mention earlier, the members table has an ID field. That's how I'm pulling all of the usernames.

For example, let's say there's user1 and user2. User1's ID is 1. User2's ID is 2. When I click on the link to User1's profile, it takes me to User2's profile, and vice versa.

Is there a way to put them in the same order?

Upvotes: 0

Views: 76

Answers (2)

Kickstart
Kickstart

Reputation: 21533

Having a quick play you can do it with something like the following (not tested)

<?php

error_reporting(E_ERROR | E_PARSE);

$sql = mysql_query("
SELECT members.username, Sub1.FreindIds
FROM members
INNER JOIN (
    SELECT user_id AS FreindIds FROM friends WHERE friend_id=$usrid
    UNION
    SELECT friend_id AS FreindIds FROM friends WHERE user_id=$usrid
) Sub1
ON members.id = Sub1.FreindIds");

$checksql = mysql_num_rows($sql);

while ($row_comp = mysql_fetch_assoc($sql)) 
{
    echo '<a href="../../member/profile?id=' . $row_comp['FreindIds'] . '">' . $row_comp['username'] . '</a><br />';
}

error_reporting(E_ALL);

?>

Upvotes: 0

Nick Humrich
Nick Humrich

Reputation: 15805

You can join the two tables before you even put them in an array. Then the data is already matched up for you.

http://www.w3schools.com/sql/sql_join.asp

Upvotes: 1

Related Questions