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
https://forums.phpfreaks.com/topic/171971-solved-array-foreach-and-implode/
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);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.