将多个数组值作为整数插入-PHP MYSQL
这可能很容易实现,但我似乎无法实现。我有一个数组$this->shippingLocations,它返回以下内容:将多个数组值作为整数插入-PHP MYSQL,php,mysql,mysqli,Php,Mysql,Mysqli,这可能很容易实现,但我似乎无法实现。我有一个数组$this->shippingLocations,它返回以下内容: var_dump($this->shippingLocations); array(3) { [0]=> string(2) "14" [1]=> string(1) "5" [2]=> string(1) "1" } 我想在mysql表中插入上述值。每一行都使用mysqli编写的语句,但作为整数。所以我把这些值转换成整数 foreach($this-&
var_dump($this->shippingLocations);
array(3) { [0]=> string(2) "14" [1]=> string(1) "5" [2]=> string(1) "1" }
我想在mysql表中插入上述值。每一行都使用mysqli编写的语句,但作为整数。所以我把这些值转换成整数
foreach($this->shippingLocation as $key => $val) {
$shipArray[$key] = (int)$val;
}
由此得出以下结论:
var_dump($shipArray);
array(3) { [0]=> int(14) [1]=> int(5) [2]=> int(1) }
然后获取数组中的项数
$addCountry = count($shipArray);
并为它们中的每一个运行查询
for ($i = 0; $i < $addCountry; $i++) {
$data = array (
"item_id" => $lastItemID,
"country_id" => $shipArray[$i]
);
// types for bind_param, table name and array(keys are table columns and values are data for columns) which are passed to a working insert function
$db->insert('ii', 'countries_ship', $data);
}
我收到的通知是未定义的偏移量:1。2.3取决于数组中的项目数。发布工作代码。我唯一的问题是for语句中的重复名称
//$this->shippingLocations is an array with string values
//changing string to array for all values
foreach($this->shippingLocation as $key => $val) {
$shipArray[$key] = (int)$val;
}
//counting items in new array
$addCountry = count($shipArray);
//add each item in `countries_ship` table
for ($i = 0; $i < $addCountry; $i++) {
//creating array for mysql query
$data = array (
"item_id" => $lastItemID,
"country_id" => $shipArray[$i]
);
//insert into table
$db->insert('ii', 'countries_ship', $data);
}
请在$db->insert方法后面发布代码。它一定是在那里调用prepare/execute,但我想看看如何。str_repeat看起来不正确,因为mysqli::bind_param的第一个参数是一个没有空格的字符串,就像IIS中的8个整数和一个字符串一样。PHP类型的整数与字符串对MySQLi来说并不重要。只要它们与i绑定,就可以了——您不需要强制转换它们。我注意到这里您正在覆盖for循环中的$shipArray$shipArray=array'item\u id'=>$lastItemID。。。。您必须使用不同的变量,或者附加到$shipArray。这对我来说还不明显。我想附加到$shipArray。。。我该怎么做?我希望$shipArray具有精确的键和值,但值应该是整数。使用[]附加语法:$ahipArray[]=array'item_id'=>$lastItemID….我是说您稍后在文章底部附近的for循环中使用相同的变量$shipArray。在这里,您将分配$shipArray=array。。。同时也在同一分配中尝试引用$shipArray[$i]。您有命名冲突。因此,循环[0]中第一个索引之后未定义的偏移量1,2,3,$shipArray不再是一个多项目数组。它已被覆盖为单个关联数组。