如何将这些结果作为每个键名的一条记录插入数据库? 这两个数组将始终具有相同数量的记录和键名。
[size_chart_data] =Array (
[Width] =Array (
[Small] =18
[Medium] =20
[Large] =22
[X-Large] =24
[2X-Large] =26
[3X-Large] =28
[4X-Large] =30
[5X-Large] =32
)
[Height] =Array (
[Small] =28
[Medium] =29
[Large] =30
[X-Large] =31
[2X-Large] =32
[3X-Large] =33
[4X-Large] =34
[5X-Large] =35
)
)
我使用以下sql插入数据库:
$chartData = db_insert('pa_size_chart_data')
->fields(array(
'width',
'height',
));
非常感谢你的时间。如果有任何需要澄清,请告诉我。 亚伦
答案 0 :(得分:0)
我想你应该这样做:
$size_chart_data = array();
foreach ($size_chart_data['Width'] as $key => $value) {
$db_data = array();
if (!empty($size_chart_data['Height'][$key])) {
$db_data = array(
'size_id' => $key, // this is size_id
'width' => $value, // this is width
'height' => $size_chart_data['Height'][$key], // this is height
);
// check what you've got
print_r($db_data);
// add $db_data to database, I suppose it's like
$chartData = db_insert('pa_size_chart_data')
->fields($db_data);
}
}
答案 1 :(得分:0)
这就是答案。特别感谢@u_mulder和@blackandorangecat所有有用的想法! 在问题中我只包括宽度和高度。但我觉得如果我加入第3级,对其他人可能更有帮助。所以答案包括宽度,高度和宽度。套筒。
$size_chart_data = array();
foreach ($size_chart_data['Width'] as $key => $value) {
// floatval() is changing string results to float
$value = floatval($value);
if (!empty($size_chart_data['Height']) && !empty($size_chart_data['Sleeve'])) {
// floatval() is changing string results to float
$size_chart_data['Height'][$key] = floatval($size_chart_data['Height'][$key]);
$size_chart_data['Sleeve'][$key] = floatval($size_chart_data['Sleeve'][$key]);
$db_data = array(
'width' => $value, // this is width
'height' => $size_chart_data['Height'][$key], // this is height
'sleeve' => $size_chart_data['Sleeve'][$key], // this is the sleeve
);
} elseif (!empty($size_chart_data['Height'])) {
$size_chart_data['Height'][$key] = floatval($size_chart_data['Height'][$key]);
$db_data = array(
'width' => $value, // this is width
'height' => $size_chart_data['Height'][$key], // this is height
'sleeve' => null, // this is the sleeve
);
} elseif (!empty($size_chart_data['Width'])){
$db_data = array(
'width' => $value, // this is width
'height' => null, // this is height
'sleeve' => null, // this is the sleeve
);
}
$sizeArr = array($db_data);
$chartData = db_insert('pa_size_chart_data')
->fields(array(
'width',
'height',
'sleeve',
));
foreach ($sizeArr as $sizeRec) {
$chartData->values($sizeRec);
}
$chartData->execute();
}