从数组中获取价值

时间:2012-10-01 10:09:04

标签: php arrays

我有一个私人消息系统,我有这个功能,它返回对话中所有用户的ID(发件人除外):

function findOtherUsersInConversation($conversation_id) {
    $sender = findMessageSenderId($conversation_id);
    $query  = mysql_query("SELECT user_id FROM message_partecipant WHERE conversation_id =   '$conversation_id' AND user_id !=$sender");
    while ($row = mysql_fetch_array($query)) {
        $user_id = $row['user_id'];
        print_r($user_id);
    }
}

print_r返回ID(例如id100和id 101),如下所示:

100101//which is not what i'm trying to do

我有另一个函数可以在数据库中找到用户名,因此对于每个用户ID,我希望以这种格式获取用户名:

echo usernameFromId($user_id)// this should echo out all the username like this (user a, user b, user c)

我想我必须做一个foreach循环,但我想不出怎么做。

4 个答案:

答案 0 :(得分:1)

试试这个:

function findOtherUsersInConversation($conversation_id){
    $sender = findMessageSenderId($conversation_id);
    $query =  mysql_query("SELECT user_id FROM message_partecipant WHERE conversation_id =   '$conversation_id' AND user_id !=$sender");
    $users = array();
    while ($row = mysql_fetch_array($query)) {
        $users[] = usernameFromId($row['user_id']); // fetch user name and add it to array
    }
    return implode(', ', $users); // return a string separated by commas
}

findOtherUsersInConversation(10); // conversation id 10

答案 1 :(得分:1)

试试这个

function findOtherUsersInConversation($conversation_id) {
$sender = findMessageSenderId($conversation_id);
$query  = mysql_query("SELECT user_id FROM message_partecipant WHERE conversation_id =   '$conversation_id' AND user_id !=$sender");
$cnt=0;
while ($row = mysql_fetch_array($query)) {
    $user_id = $row['user_id'];
   if($cnt==0):
       $comma_separated .=$user_id;
   else: 
      $comma_separated .=",".$user_id;
   endif;   
   $cnt++;
}
 return $comma_separated
}

$getID=findOtherUsersInConversation(10); 

$arrayID= explode( ',', $getID);// split string from comma(,)

print_r($arrayID);// print all ID's as you want

愿这会帮助你。

答案 2 :(得分:0)

function findOtherUsersInConversation($conversation_id){
  $sender = findMessageSenderId($conversation_id);
  $query =  mysql_query("SELECT user_id FROM message_partecipant WHERE conversation_id ='$conversation_id' AND user_id !=$sender");
  $usernameArr = array();
  while ($row = mysql_fetch_array($query)) {
    $user_id= $row['user_id'];
    array_push($usernameArr, usernameFromId($user_id));
  }

  $comma_separated = implode(",", $usernameArr);

  echo $comma_separated;
}

答案 3 :(得分:0)

如果您只想查看您的信息阵列,请尝试:

var_dump($array);

否则在foreach中尝试输出你的数组:

foreach($array as $var){
    echo $var;
}