我将变量$users
设置为类似于下面的
Array(
[4] => Array(
[userid] => 4
[name] => Mike
[gender] => M
)
[5] => Array(
[userid] => 5
[name] => Sally
[gender] => F
)
[6] => Array(
[userid] => 6
[name] => Steve
[gender] => M
)
)
然后我有代码循环遍历此数组以调用函数来计算年龄。
foreach($users as $user){
$age = getUserAge($user->id);
}
如何使用变量$age
并将其添加到$users
以获得跟随数组?
Array(
[4] => Array(
[userid] => 4
[name] => Mike
[gender] => M
[age] => 35
)
[5] => Array(
[userid] => 5
[name] => Sally
[gender] => F
[age] => 24
)
[6] => Array(
[userid] => 6
[name] => Steve
[gender] => M
[age] => 32
)
)
答案 0 :(得分:13)
foreach($users as &$user){
$age = getUserAge($user['userid']);
$user['age'] = $age;
}
精简版:
foreach($users as &$user){
$user['age'] = getUserAge($user['userid']);
}
答案 1 :(得分:6)
foreach($users as $index => $user) {
$users[$index]['age'] = getUserAge($user['userid']);
}