Page 1 of 1

Traversing array...

Posted: Sat Aug 15, 2009 4:42 pm
by Wolf_22
Using print_r, I have the following in my array:

Code: Select all

Array ( 
     [0] => Array ( 
          [0] => stdClass Object ( 
               [id] => 1 
               [user_login] => admin ) 
          [1] => stdClass Object ( 
               [id] => 2 
               [user_login] => test ) 
           ) 
)
I'm having a difficult time understanding why stdClass has been placed within the array but more importantly, I'm having a harder time getting my foreach to work on it.

What I want it to do is the following:
echo id and user_login.

The foreach I tried to use is this:

Code: Select all

foreach($todo_users[0] as $key=>$val){
        echo $key.'=>'.$val."\n";
    }
Could someone help me get this straitened out? Please let me know if you need more information.

Re: Traversing array...

Posted: Sat Aug 15, 2009 4:52 pm
by aceconcepts
Need more info. What are you doing? Explain more.

Re: Traversing array...

Posted: Sat Aug 15, 2009 5:02 pm
by Wolf_22
The users represent everyone who is registered and who is of type "administrator." The id is simply their user id from within the database. What I'm trying to do is take this query that is inside the array and output their results in a foreach where the id and username is used for further conditional processing.

Something sorta like this:

Code: Select all

foreach user as id=>user{
echo "{$username}\'s id is {$id}.<br />";
}
The function I'm using to execute the aforementioned query is the following:

Code: Select all

function get_vtl_user_roles(){
    global $vtl_roles,$vtldb;
    $this_role = "'[[:<:]]administrator[[:>:]]'";
    $query = "SELECT DISTINCT id, user_login FROM $vtldb->users WHERE ID = ANY (SELECT DISTINCT user_id FROM $vtldb->usermeta WHERE meta_value RLIKE 'administrator') ORDER BY ID ASC LIMIT 10000";
    $users_of_this_role[] = $vtldb->get_results($query);
    return $users_of_this_role;
}
That function grabs the usernames and ids from the appropriate mysql table and attempts to insert them into "$users_of_this_role" array. Unfortunately, I can't seem to understand why the array is making it into a multi-dimensional one. The function "get_results()" is from Wordpress (as is most of this).

Re: Traversing array...

Posted: Sat Aug 15, 2009 5:41 pm
by aceconcepts
The function get_results() is most likely returning an array thus making your final array a multi-dimensional one.

A foreach() loop works just as you used it in your initial post. However, you seem to have additional keys and values with that std_class object.

So if this is the array returned by get_results() then an additional nested foreach() could suffice.

Re: Traversing array...

Posted: Sat Aug 15, 2009 10:09 pm
by Wolf_22
Makes sense. :)