繁体   English   中英

将多个数组值插入为整数-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);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM