php数组值在循环中被替换

时间:2015-06-26 12:35:56

标签: php arrays loops override

我只是尝试遍历数据库查询的获取结果并将它们存储在新数组中。所以我的第一次尝试是这样的:

$stmt = $db->prepare("SELECT name, uid, coordinates, address, timestamp FROM my_table WHERE uid = ?");
$stmt->bind_param("s", $uid);

$stmt->execute();
$meta = $stmt->result_metadata();

while ($field = $meta->fetch_field()) 
{ 
    $parameters[] = &$row[$field->name]; 
}

call_user_func_array(array($stmt, 'bind_result'), $parameters);

$results = array();
while ($stmt->fetch()) 
{
    $results[] = $row;

    echo "Results: <pre>";
    print_r($results);
    echo "</pre><br />";
}

编辑:这是一个MySQL(i)语句,$ row本身已定义并包含查询数据。

但结果却出人意料:

(由于隐私措施,我只能向您显示时间戳,但您仍然可以看到我的意思)

Results: Array
(
[0] => Array
    (
        [name] => ---
        [uid] => ---
        [coordinates] => ---
        [address] => --
        [timestamp] => 1395607435.826
    )
)

Results: Array
(
[0] => Array
    (
        [name] => ---
        [uid] => ---
        [coordinates] => ---
        [address] => ---
        [timestamp] => 1395607047.357
    )

[1] => Array
    (
        [name] => ---
        [uid] => ---
        [coordinates] => ---
        [address] => ---
        [timestamp] => 1395607047.357
    )
)

Results: Array
(
[0] => Array
    (
        [name] => ---
        [uid] => ---
        [coordinates] => ---
        [address] => ---
        [timestamp] => 1395607158.907
    )

[1] => Array
    (
        [name] => ---
        [uid] => ---
        [coordinates] => ---
        [address] => ---
        [timestamp] => 1395607158.907
    )

[2] => Array
    (
        [name] => ---
        [uid] => ---
        [coordinates] => ---
        [address] => ---
        [timestamp] => 1395607158.907
    )
)

我错过了什么? 为什么数组每次都被覆盖而不仅仅是附加?

2 个答案:

答案 0 :(得分:0)

使用以下代码

$results = array();
$i=0; // using this variable so that you can have a track of the index that you are in, if you do not wish to use this increment variable then you can remove it.
while ($row = $stmt->fetch()) 
{
    $results[] = $row;

    $i++;
}


echo "Results: <pre>";
print_r($results);
echo "</pre><br />";

答案 1 :(得分:0)

目前我只是使用我的解决方法。如果应该有更高性能,请告诉我。

$results = array();
$index = 0;
while ($stmt->fetch()) 
{   
    $data                = array();
    $data["name"]        = $row["name"];
    $data["uid"]         = $row["uid"];
    $data["coordinates"] = $row["coordinates"];
    $data["address"]     = $row["address"];
    $data["timestamp"]   = $row["timestamp"];

    $results[$index] = $data;
    $index++;
}