改变多维数组的值


Changing values of multi dimentional arrays

我有一个mysql查询的结果在一个多维数组如下:

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

我想循环遍历这些,检查[userlevel]值和if == '5'的值,然后修改[name]值。我们的想法是在这些用户的旁边提供一个视觉指示器,这些用户是特定的用户级别。

我试过循环使用foreach,但我不能让它工作。

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

注意:符号&在这里非常重要。

另外:

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

来自PHP文档站点

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.

你试过了吗?这样应该可以工作。

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