Jump to content

[SOLVED] array foreach and implode


irkevin

Recommended Posts

I've been searching for a solution about this but im stuck. Here's is a problem..

 

I have this code:

$new_users = User::find_by_date();

echo "<pre>";
print_r($new_users);
echo "</pre>";

 

The result is :

Array
(
    [0] => User Object
        (
            [id] => 
            [firstname] => 
            [lastname] => 
            [username] => jkjkjkjkjkjk
            [password] => 
            [dob] => 
            [email] => 
            [location] => 
            [date_created] => 
        )

    [1] => User Object
        (
            [id] => 
            [firstname] => 
            [lastname] => 
            [username] => tester
            [password] => 
            [dob] => 
            [email] => 
            [location] => 
            [date_created] => 
        )

)

 

When i do a foreach to get the data, i do it like this:

$new_users = User::find_by_date();


foreach($new_users as $users){
echo $users->username.'<br />';
}

 

It outputs the username like it should. EG:

 

jkjkjkjkjkjk

tester

 

What i really want is to seperate then with comma using the implode function.

 

I tried this:

 

foreach($new_users as $users){
echo implode(", ",$users);
}

 

But i get

 

 

Warning: implode() [function.implode]: Invalid arguments passed in C:\wamp\www\mu-anime\var.php on line 8

 

Warning: implode() [function.implode]: Invalid arguments passed in C:\wamp\www\mu-anime\var.php on line 8

 

 

I dont know what to do anymore, can someone help me plz?

Link to comment
Share on other sites

Implode requires an array as the 2nd parameter. You are attempting to implode a string that you are retrieving from

each user object. What you must do is create an array of names from each object, then implode it.

<?php
$new_users = User::find_by_date();
$users = array();
foreach($new_users as $userObj){
$users[] = $userObj->username;
}
print implode(",", $users);
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.