将键值对添加到现有数组

时间:2013-12-21 04:51:09

标签: php arrays loops

我将变量$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
    )
)

2 个答案:

答案 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']);
}