Changing values of multi dimentional arrays

I have the results of a mysql query in a multi dimentional array as follows:

Array ( 
[0] => stdClass Object ( [name] => john doe [id] => [email protected] [userlevel] => 1 ) 
[1] => stdClass Object ( [name] => mary jane [id] => [email protected] [userlevel] => 5 ) 
[2] => stdClass Object ( [name] => joe blow [id] => [email protected] [userlevel] => 1 )
);

I would like to loop through these, check the value of the [userlevel] value and if == '5', then modify the [name] value. The idea is to give a visual indicator next to those users that are a certain userlevel.

I've tried to loop through using foreach, but I can't get it to work.

Upvotes: 0

Views: 65

Answers (3)

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28889

foreach ($array as $i => &$user) {
    if ($user->userlevel == 5) {
        $user->name = 'foo';
    }
}

NOTE: The ampersand & is very important here.

Alternatively:

for ($i = 0, $arrayLen = count($array); $i < $arrayLen; ++$i) {
    if ($array[$i]->userlevel == 5) {
        $array[$i]->name = 'foo';
    }
}

Upvotes: 2

Luc M
Luc M

Reputation: 17314

From PHP documentation site

Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.

Upvotes: 0

Viktor
Viktor

Reputation: 3536

What have you tried? Something like this should work.

foreach ($result as $i => $item)
{
    if ($item->userlevel == 5)
        $result[$i]->name = 'modified name';
}

Upvotes: -1

Related Questions