如何在PHP中为现有数组添加新的键值

时间:2014-09-29 06:27:49

标签: php mysql associative-array keyvaluepair

我在PHP中有一个表单,它带有两个值:server_iduser_id(可以由','分隔多个值)。我从表中检索一些数据并将它们存储为数组。使用相同的server_iduser_id,我想从另一个表中检索其他表,但将它们存储到同一个数组中。

这是我到目前为止所做的。

//Data from PHP form stored in array
$inputData = Array ( [server_id] => 10 
                        [user_id] => Array ( [0] => 111[1] => 222) ) 

//Existing array storing data retrieved from persons table
$userData = 
Array 
( 
    [0] => Array 
        (

            [user_id] => 111
            [server_id] => 10
            [user_name] => Harry Pottter 
            [user_age] => 18 ) 

    [1] => Array 
        ( 
            [user_id] => 222 
            [server_id] => 10 
            [user_name] => Hermione
            [user_age] => 18 ) 
)

//retrieving additional data from user_contact table
$sql = "SELECT user_phone, user_address FROM user_contact 
        WHERE user_id = ? AND server_id = ?";

foreach($user_id as $user)
{
    $statement= $DB->link->prepare($sql);
    $statement->bind_param("si", $server_id, $user);
    $statement->execute();

    if($resultSet = $statement->get_result())
    {
        while($row = $resultSet->fetch_assoc())
        {
            userData[$key]['user_phone'] = $row['user_phone'];
            userData[$key]['user_address'] = $row['user_address'];
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试使用array_push()

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>