如何从下面的代码中获取数组值?并使用while loop
保存非空的数据。
不太确定需要从代码中添加什么。
if(!empty($bookslot['t_deep'])) :
$tw_deep = 'deep_wrap';
elseif(!empty($bookslot['t_eyelashes'])) :
$tw_eyelashes = 'eyeLashes_wrap';
elseif(!empty($bookslot['t_holistic'])) :
$tw_holistic = 'holistic_wrap';
elseif(!empty($bookslot['t_male_nail'])) :
$tw_male_nail = 'male_nail_wrap';
endif;
$arr[] = array($tw_deep, $tw_eyelashes, $tw_holistic, $tw_male_nail);
$db->query("INSERT INTO checked_treatments (treatment_group, id_treatment, id_booking, b_ref) VALUES('$arr', '1','$id_bookslot', '$b_ref')");
在treatment_group中,数组返回Array instead of 'deep_wrap, etch..
期待数据库:
Array 1 123 abc // <-- result above code
--------------------------------------------------------
deep_wrap 1 123 abc
holistic_wrap 2 123 abc
答案 0 :(得分:1)
你想做的就是这个(我想):
$arr = array($tw_deep, $tw_eyelashes, $tw_holistic, $tw_male_nail);
$arrPlode = implode(', ', $arr);
$db->query("INSERT INTO checked_treatments (treatment_group, id_treatment, id_booking, b_ref)
VALUES('$arrPlode', '1','$id_bookslot', '$b_ref')");
这是一个带有查询回应的演示:http://codepad.org/3NgGu1Tm
或强>
为每个if:
创建一个新查询if(!empty($bookslot['t_deep'])) {
$db->query("INSERT INTO checked_treatments (treatment_group, id_treatment, id_booking, b_ref)
VALUES('deep_wrap', '1','$id_bookslot', '$b_ref')");
}
if(!empty($bookslot['t_eyelashes'])) {
$db->query("INSERT INTO checked_treatments (treatment_group, id_treatment, id_booking, b_ref)
VALUES('eyeLashes_wrap', '1','$id_bookslot', '$b_ref')");
}
if(!empty($bookslot['t_holistic'])) {
$db->query("INSERT INTO checked_treatments (treatment_group, id_treatment, id_booking, b_ref)
VALUES('holistic_wrap', '1','$id_bookslot', '$b_ref')");
}
if(!empty($bookslot['t_male_nail'])) {
$db->query("INSERT INTO checked_treatments (treatment_group, id_treatment, id_booking, b_ref)
VALUES('male_nail_wrap', '1','$id_bookslot', '$b_ref')");
}
或加强查询:
$concat = array();
if(!empty($bookslot['t_deep'])) {
$concat[] = "('deep_wrap', '1','$id_bookslot', '$b_ref')";
}
if(!empty($bookslot['t_eyelashes'])) {
$concat[] = "('eyeLashes_wrap', '1','$id_bookslot', '$b_ref')";
}
if(!empty($bookslot['t_holistic'])) {
$concat[] = "('holistic_wrap', '1','$id_bookslot', '$b_ref')";
}
if(!empty($bookslot['t_male_nail'])) {
$concat[] = "('male_nail_wrap', '1','$id_bookslot', '$b_ref')";
}
$db->query(build_insert_query('checked_treatments',
'treatment_group, id_treatment, id_booking, b_ref', $concat));
function build_insert_query($table, $cols, $values){
$return = "INSERT INTO $table ($cols) VALUES";
$val_length = count($values);
foreach($values as $key=>$val){
$return .= $val;
if($key < ($val_length-1)){ $return .= ", "; }
}
return $return;
}
以上是虚假值的演示:http://codepad.org/ox4kG43b
答案 1 :(得分:0)
删除声明中的方括号。你正在制作一个三维数组
$arr = array($tw_deep, $tw_eyelashes, $tw_holistic, $tw_male_nail);
在您的查询中,您仍然需要取消引用数组以通过指定索引来获取值
$db->query("INSERT INTO checked_treatments (treatment_group, id_treatment, id_booking, b_ref) VALUES('$arr[0]', '1','$id_bookslot', '$b_ref')");
索引为0将返回$tw_deep