我正在使用 foreach
循环在插入数据库之前用参数类型和参数值填充array
。一切工作正常并发布到数据库,但我不明白为什么当将两个值添加(作为引用)到数组时它会发送相同的值。我厌倦了调用 unset();
但它不起作用。
function insertUsers($db, $sql, $vals){
$stmt= $db->prepare($sql);
$types='';
$types= $types ?: str_repeat("s", count($vals));
$inputArray [] = &$types;
foreach($vals as $key=>$value){
$inputArray[]= &$value;
unset($key);
}
print_r($inputArray);
call_user_func_array(array($stmt, 'bind_param'), $inputArray);
$stmt->execute();
$stmt->close();
}
最终结果是:
Array
(
[0] => ss
[1] => tyuty (note this value changes to the last value)
[2] => tyuty
)
最佳答案
您需要从 foreach()
中删除 &
;-
foreach($vals as $key=>&$value){ // put & here
$inputArray[]= $value; // remove & from here and unset() not needed actually
}
并在函数参数内添加 &
:-
function insertUsers($db, $sql, &$vals){
关于php - foreach 循环填充 call_user_func_array 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47839297/