开发者

Changing values of multi dimentional arrays

开发者 https://www.devze.com 2023-04-09 23:43 出处:网络
I have the results of a mysql query in a multi dimentional array as follows: Array ( [0] => stdClass Object ( [name] => john doe [id] => john@doe.com [userlevel] => 1 )

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

Array ( 
[0] => stdClass Object ( [name] => john doe [id] => john@doe.com [userlevel] => 1 ) 
[1] => stdClass Object ( [name] => mary jane [id] => mary@jane.com [use开发者_C百科rlevel] => 5 ) 
[2] => stdClass Object ( [name] => joe blow [id] => joe@blow.com [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.


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';
    }
}


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.


What have you tried? Something like this should work.

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

精彩评论

暂无评论...
验证码 换一张
取 消