我在多维数组中有一个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]值的值,如果=='5',则修改[name]值。我们的想法是在那些用户级别的用户旁边提供一个可视指示符。
我试图使用foreach循环,但我无法让它工作。
答案 0 :(得分:2)
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';
}
}
答案 1 :(得分:0)
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.
答案 2 :(得分:-1)
你有什么尝试?这样的事情应该有效。
foreach ($result as $i => $item)
{
if ($item->userlevel == 5)
$result[$i]->name = 'modified name';
}