PHP MySQLi fetch "array push"覆盖数据

标签 php mysql arrays mysqli

我有 2 个数组:

$arr = [];

$tempArray = [
    'val1' => "xxx",
    'val2' => 0,
    'val3' => 0
];

然后在我的 mysql 查询中,我用当前行的值填充临时数组,最后将他插入 $arr:

$stmt->bind_result($tempArray["val1"], $tempArray["val2"], $tempArray["val3"]);

while ( $stmt->fetch () ) {
    array_push($arr, $tempArray);
}

问题是,在每个循环中,“array_push”都会覆盖 $arr 中的数据。

例如,我在 $stmt->fetch() 中循环了 3 次。

<强>1。循环

$tempArray = [
    'val1' => "Hello",
    'val2' => 1,
    'val3' => 2
]

$arr = [
    0 = [
        'val1' => "Hello",
        'val2' => 1,
        'val3' => 2
    ];
]

<强>2。循环

$tempArray = [
    'val1' => "Stack",
    'val2' => 3,
    'val3' => 4
]

$arr = [
    0 = [
        'val1' => "Stack",
        'val2' => 3,
        'val3' => 4
    ],
    1 = [
        'val1' => "Stack",
        'val2' => 3,
        'val3' => 4
    ];
]

<强>3。循环

$tempArray = [
    'val1' => "Overflow",
    'val2' => 5,
    'val3' => 6
]

$arr = [
    0 = [
        'val1' => "Overflow",
        'val2' => 5,
        'val3' => 6
    ],
    1 = [
        'val1' => "Overflow",
        'val2' => 5,
        'val3' => 6
    ],
    2 = [
        'val1' => "Overflow",
        'val2' => 5,
        'val3' => 6
    ]
]

我以前从未见过这种行为,我也不知道为什么会这样。

最后我想要的是这样的:

$arr = [
    0 = [
        'val1' => "Hello",
        'val2' => 1,
        'val3' => 2
    ],
    1 = [
        'val1' => "Stack",
        'val2' => 3,
        'val3' => 4
    ],
    2 = [
        'val1' => "Overflow",
        'val2' => 5,
        'val3' => 6
    ]
]

$stmt 类(@Stevish 请求)

$query = "...";
if ( $stmt = $this->db->prepare($query)) {
        $stmt->bind_param('i',  $xxx);
        $stmt->execute();
        $stmt->store_result();
        $$stmt->bind_result($tempArray["val1"], $tempArray["val2"], $tempArray["val3"]);
        while ( $stmt->fetch () ) {
            $arr[] = $tempArr;
        }
    }

最佳答案

问题是您将对 $tempArray 的引用插入到 $arr 中。然后你改变引用。在第三个循环中,您有 3 个对同一个数组的引用。这就是值以这种方式显示的原因……您可以用一种相当不直观的方式解决这个问题。

尝试:

$stmt->bind_result($tempArray["val1"], $tempArray["val2"],$tempArray["val3"]);
while ( $stmt->fetch () ) {
    $x = $tempArray; //This copies the values of $tempArray to $x and each loop will create a new x.
    array_push($arr, $x);
}

关于PHP MySQLi fetch "array push"覆盖数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32671490/

相关文章:

java - 如何在Java中检索给定范围的子数组中的第k个元素?

java - 在 Java 中,如何更有效地附加字符串?

python - 调整 numpy.memmap 数组的大小

php - 返回上次状态的 ajax 页面?

php - 解析 youtube 链接 PHP

php - 如何修复在 "localhost/wordpress"上建立数据库连接时出错

php - 通过列的第一个字母从 MySQL 表中选择 COUNT

php - ffmpeg 批量生成多张图片

php - 从 RedBean 3.5 升级到 RedBean 4 的过程

php - 释放 PDO 准备好的语句 (DEALLOCATE PREPARE)