如何在现有的关联数组中插入新的键值对?

时间:2013-09-03 11:33:03

标签: php arrays

我有以下关联数组:

Array
(
    [0] => Array
        (
            [user_id] => 9def02e6337b888d6dbe5617a172c18d
            [user_first_name] => Ashutosh
            [user_last_name] => Modi
            [user_email] => ashutosh.modi@gmail.com
            [user_status] => enable
            [user_subscription] => lifetime
            [user_registered_type] => online
            [user_reg_date] => 1325581397
        )

    [1] => Array
        (
            [user_id] => a6d22e4cc3f65778a60b359842bcec82
            [user_first_name] => Dilip
            [user_last_name] => Modi
            [user_email] => dm.modi@gmail.com
            [user_status] => enable
            [user_subscription] => period
            [user_registered_type] => online
            [user_reg_date] => 1325152066
        )


)

它有两把钥匙。现在我有另一个名为$user_data的数组,它具有以下输出:

Array
(
    [user_state] => Rajasthan
    [user_city] => Jhunjhunu
)

我想将此键值对添加到上面的数组中。上面的数组只是for循环的第一次迭代,所以上面的值被插入到第一个数组元素中。第二个数组元素将具有不同的值。我想以下面的方式得到结果。你能帮助我实现这个目标吗?提前谢谢。

Array
    (
        [0] => Array
            (
                [user_id] => 9def02e6337b888d6dbe5617a172c18d
                [user_first_name] => Ashutosh
                [user_last_name] => Modi
                [user_email] => ashutosh.modi@gmail.com
                [user_status] => enable
                [user_subscription] => lifetime
                [user_registered_type] => online
                [user_reg_date] => 1325581397
                [user_state] => Rajasthan
                [user_city] => Jhunjhunu
            )

        [1] => Array
            (
                [user_id] => a6d22e4cc3f65778a60b359842bcec82
                [user_first_name] => Dilip
                [user_last_name] => Modi
                [user_email] => dm.modi@gmail.com
                [user_status] => enable
                [user_subscription] => period
                [user_registered_type] => online
                [user_reg_date] => 1325152066
                 [user_state] => Tamilnadu
                [user_city] => Chennai
            )


    )

2 个答案:

答案 0 :(得分:2)

<?php
    foreach($user_data as $key => $val){
        $original_array[$key]['user_state'] = $val['user_state'];
        $original_array[$key]['user_city'] = $val['user_city'];
    }

假设2个数组具有相同的键

答案 1 :(得分:2)

尝试使用array_merge

foreach ($users as &$user)
{
    $user = array_merge($user, $user_data);
}

var_dump($users);