【问题标题】:Inserting parts of a multidimensional array into a mysql database将多维数组的一部分插入 mysql 数据库
【发布时间】:2014-06-27 22:32:48
【问题描述】:

下面是从 Magento api 调用返回的数组的一部分。我如何能够遍历所有记录并将 parent_id、base_price、sku 和 name 键的值插入 MySQL 数据库:

$testarray

array(2) {
  [0]=>
  array(5) {
    ["store_id"]=>
    string(1) "1"
    ["base_grand_total"]=>
    string(3) "200"
    ["invoice_id"]=>
    string(1) "3"
    ["order_increment_id"]=>
    string(1) "2"
    ["items"]=>
    array(5) {
      ["parent_id"]=>
      string(1) "1"
      ["base_price"]=>
      string(8) "1400.000"
      ["tax_amount"]=>
      string(8) "120.2300"
      ["sku"]=>
      string(8) "testsku1"
      ["name"]=>
      string(9) "testprod1"
    }
  }
  [1]=>
  array(5) {
    ["store_id"]=>
    string(1) "1"
    ["base_grand_total"]=>
    string(3) "300"
    ["invoice_id"]=>
    string(1) "4"
    ["order_increment_id"]=>
    string(1) "3"
    ["items"]=>
    array(5) {
      ["parent_id"]=>
      string(1) "2"
      ["base_price"]=>
      string(8) "1000.000"
      ["tax_amount"]=>
      string(8) "100.5400"
      ["sku"]=>
      string(8) "testsku2"
      ["name"]=>
      string(9) "testprod2"
    }
  }
}

这是我目前所拥有的代码:

foreach ($testarray as $row)
    {
    mysqli_query($con, "INSERT INTO order_sku (parent_id, base_price, tax_amount, sku, name) VALUES ('$row[parent_id]', '$row[base_price]', '$row[tax_amount]', '$row[sku]', '$row[name]')");
    }

【问题讨论】:

  • $row['items']['parent_id']...等
  • 我收到“通知:数组到字符串的转换”我需要在这里使用 implode 函数吗
  • 您可以尝试将其转换为字符串 ... string($row['items']['parent_id']);

标签: php mysql arrays magento multidimensional-array


【解决方案1】:

您已经在使用MYSQLI_ 函数,请利用准备好的语句。您需要在内部使用另一个 foreach 循环来访问 items 索引值。示例:

$testarray = array(
    array(
        'store_id' => '1', 
        'base_grand_total' => '200', 
        'invoice_id' => '3', 
        'order_increment_id' => '2',
        'items' => array('parent_id' => '1', 'base_price' => '1400.000', 'tax_amount' => '120.2300', 'sku' => 'testsku1', 'name' => 'testprod1')
    ),
    array(
        'store_id' => '1', 
        'base_grand_total' => '300', 
        'invoice_id' => '4', 
        'order_increment_id' => '3',
        'items' => array('parent_id' => '2', 'base_price' => '1000.000', 'tax_amount' => '100.5400', 'sku' => 'testsku2', 'name' => 'testprod2')
    ),
);

$con = new mysqli('localhost', 'username', 'password', 'database');
foreach($testarray as $values) {
    foreach($values['items'] as $item) {
        $stmt = $con->prepare('INSERT INTO order_sku (parent_id, base_price, tax_amount, sku, name) VALUES (?, ?, ?, ?, ?)');
        // provided the columns are all VARCHAR
        $stmt->bind_param('sssss', $item['parent_id'], $item['base_price'], $item['tax_amount'], $item['sku'], $item['name']);
        $stmt->execute();
    }
}

【讨论】:

  • 我在上面输入了错误的数组,但您的代码示例绝对让我朝着正确的方向前进。谢谢。
猜你喜欢
  • 2011-12-06
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 2017-05-18
  • 2015-06-08
相关资源
最近更新 更多