我正在尝试计算关联数组的值,但它并不是我想做的。
我从数据库中提取数据,因为我需要一个问题的所有答案。数据库中的答案在answer1,answer2,answer3等字段下,最多为answer20。
我要做的是计算包含数据的字段数,并忽略没有任何数据的字段。
到目前为止,这是我的代码:
<?php
$results = $db->get_results("SELECT * FROM wellness_hra_questions WHERE category='general' AND level='1' AND gender='All' AND active='yes' ORDER BY id ASC");
foreach($results as $result){
$id = $result->id;
}
$answers = $db->get_results("SELECT answer1, answer2, answer3, answer4, answer5, answer6, answer7, answer8, answer9, answer10, answer11, answer12, answer13, answer14, answer15, answer16, answer17 FROM wellness_hra_questions WHERE id=".$id."");
//$db->debug();
for( $i=1; $i <= 17; $i++) {
foreach($answers as $a_result){
$answer = 'answer';
$answer_id = $answer.$i;
$answer_id2 = $a_result->$answer_id;
$answer1 = $a_result->answer1;
$array1 = array('1'=>''.$answer1.'');
$answer2 = $a_result->answer2;
$array2 = array('2'=>''.$answer2.'');
$answer3 = $a_result->answer3;
$array3 = array('3'=>''.$answer3.'');
$answer4 = $a_result->answer4;
$array4 = array('4'=>''.$answer4.'');
$answer5 = $a_result->answer1;
$array5 = array('5'=>''.$answer5.'');
$answer6 = $a_result->answer6;
$array6 = array('1'=>''.$answer6.'');
}
if($answer1 == TRUE){
$newvalue1 = $array1;
}
if($answer2 == TRUE){
$newvalue2 = $array2;
}
if($answer3 == TRUE){
$newvalue3 = $array3;
}
if($answer4 == TRUE){
$newvalue4 = $array4;
}
if($answer5 == TRUE){
$newvalue1 = $array5;
}
if($answer1 == TRUE){
$newvalue6 = $array6;
}
$newarray = array_merge($newvalue1,$newvalue2, $newvalue3, $newvalue4, $newvalue5);
$count = count($newarray, COUNT_RECURSIVE);
echo $count;
}
?>
答案 0 :(得分:1)
你需要在这里进行代码清理 - 如果你想要的是一个计数,array_merge
仅用于此目的,这应该做我认为你想做的事情:
for( $i=1; $i <= 17; $i++) {
foreach($answers as $a_result){
$answer_id = 'answer'.$i;
$answer_id2 = $a_result->$answer_id;
$thisCount = 0;
$newarray = array();
for($j = 1; $j < 7; $j++) {
$var = "answer" . $j;
$$var = ${"a_result->answer" . $j};
if (strlen($$var) > 0) {
$arrayID = "array" . $j;
$$arrayID = array((string)$j => $$var);// I don't think you need this but if you do included array_merge here
array_merge($newarray, $$arrayID);
$thisCount++;
}
}
echo $count;
print_r($newarray); // show the contents of the merged arrays
}// end foreach
}//end for