• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Output loop to string

#1
[eluser]codex[/eluser]
Ok guys,

this is probably a silly question, but I just can't see it (it's late and I had a bit of alcohol ;-) ).

I'm making a private messaging system and this part is where the new message is being inserted. See the loop below: $recipients is an array that holds the id's of the multiple receivers. What I want to do is take the array, query the db for the corresponding username, create a variable of the usernames and insert that together with the new message. The variable is just a simple string, example: 'jason, perry, luke, antoine'.

How do I write the loop to the variable?? Help is greatly appreciated!

Code:
foreach ($recipients as $recipient)
{
    $this->db->select('user_name');
    $this->db->where('user_id', $recipient);
    $query = $this->db->get('users');
    $user = $query->result_array();
            
    $str = $user[0]['user_name'] .', '; // this is obviously not the way to do it
}

#2
[eluser]Future Webs[/eluser]
would you not want to return a row rather then an array

#3
[eluser]Armchair Samurai[/eluser]
Do one DB query to get the names, then do the loop rather than hitting up the DB multiple times. For example, something like:
Code:
$this->db->select('user_name');
$this->db->where_in('user_id', $recipients);
$query = $this->db->get('users');
$result = $query->result();

foreach ($result as $val)
    $arr[] = $val->user_name;

$str = implode(', ', $arr);

#4
[eluser]codex[/eluser]
[quote author="Armchair Samurai" date="1227333500"]Do one DB query to get the names, then do the loop rather than hitting up the DB multiple times. For example, something like:
Code:
$this->db->select('user_name');
$this->db->where_in('user_id', $recipients);
$query = $this->db->get('users');
$result = $query->result();

foreach ($result as $val)
    $arr[] = $val->user_name;

$str = implode(', ', $arr);
[/quote]

Thanks armchair!

I haven't used where_in before. Guess it's time to delve deeper into mysql/queries since the way I have been doing it (hitting the db multiple times) seems to be rather inefficient.

And of course! Implode()!! Jeez...


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.