将多个数组值作为整数插入 - PHP MYSQL


Insert multiple array values as integers - PHP MYSQL

这可能很容易完成,但我似乎无法理解。我有一个数组$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 取决于数组中的项目数。

发布工作代码。我唯一的问题是 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);
}