我有这个数组:
Array (
[0] => Array
(
[0] => 2
)
[1] => Array
(
[0] => 2015-07-20
)
[2] => Array
(
[0] => 2
[1] => 5
)
[3] => Array
(
[0] => 70
[1] => 17
)
[4] => Array
(
[0] => 4
[1] =>
)
[5] => Array
(
[0] => 66
[1] => 17
)
)
现在我希望像这样更新数据库
Array
(
[0] => Array
(
[0] => 2
[1] => 2015-07-20
[2] => 2
[3] => 70
[4] => 4
[5] => 66
)
[1] => Array
(
[0] => 2
[1] => 2015-07-20
[2] => 5
[3] => 17
[4] =>
[5] => 17
)
)
有可能吗?或者qny从阵列中更新记录的其他方式?
我有这样的循环OUTPUT: -
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =2 item_id =5 before_sale_totitem_qty =70 before_sale_totitem_qty =17 after_sale_totitem_qty =4 after_sale_totitem_qty = restOfItem =66 restOfItem =17 note =NULL WHERE shop_id =2
但我想这样: -
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =2 before_sale_totitem_qty =70 after_sale_totitem_qty =4 restOfItem =66 note =NULL WHERE shop_id =2
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =5 before_sale_totitem_qty =17 after_sale_totitem_qty = restOfItem =17 note =NULL WHERE shop_id =2
任何帮助?
答案 0 :(得分:1)
如果我理解你的问题,你需要将数据从第一个数组转换为第二个数组,然后才能使这个数据变为现实吗?
如果是,则转换为具有0索引的默认值的数组。适用于多个版本,因此您可以添加索引3,5等,它仍然有效。
$default = array();
$versions = array();
foreach($array as $key => $values){
foreach($values as $version => $value){
if($version === 0){
$default[$key] = $value;
continue;
}
if(!array_key_exists($version, $versions)){
}
$versions[$version][$key] = $value;
}
}
$return = array(
0 => $default,
);
foreach($versions as $version => $versionData){
$return[$version] = $versionData+$default;
}
如果您需要foreach来构建SQL查询,请访问:
$columns = array(
'shop_id', 'datetime', 'item_id', 'before_sale_totitem_qty', 'after_sale_totitem_qty', 'restOfItem'
);
foreach($return as $version => $data){
$columnData = array();
foreach($data as $columnIndex => $value){
$columnData[] = sprintf('%s = %s', $columns[$columnIndex], $value);
}
$sql = sprintf('UPDATE update_shopwise_stock SET %s WHERE shop_id=%d', implode(', ', $columnData), $data[0]);
}
但我的个人建议不是像这样使用sql,而是使用PDO进行准备语句和更好的安全性。准备语句在这里循环:
$columns = array(
'shop_id', 'datetime', 'item_id', 'before_sale_totitem_qty', 'after_sale_totitem_qty', 'restOfItem'
);
foreach($return as $version => $data){
$columnPrepare = array();
$columnData = array();
foreach($data as $columnIndex => $value){
$columnName = $columns[$columnIndex];
$columnPrepare[] = sprintf('%s = :%s', $columnName, $columnName);
$columnData[$columnName] = $value;
}
$query = $db->prepare(sprintf("UPDATE update_shopwise_stock SET %s WHERE shop_id=:shop_id", implode(', ', $columnPrepare)));
foreach($columnData as $column => $value){
$query->bindParam(sprintf(':%s', $column), $value);
}
$query->execute();
}
一切都未经测试,可能会有一些错误,最终导致性能问题。它基于问题问题,仅显示如何解决此问题。