这可能很容易实现,但我似乎无法得到它。我有一个数组$this->shippingLocations
,它返回以下内容:
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取决于数组中的项目数。
答案 0 :(得分:0)
发布工作代码。我唯一的问题是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);
}