1
我想计算一个关联数组的值,但它没有做我想做的事。计数关联数组的数组值不工作
我从数据库中提取数据,因为我需要所有问题的答案。数据库中的答案在答案1,答案2,答案3等字段中,最多可回答20。
我想要做的是统计包含数据的字段的数量,并忽略没有任何数据的字段。
这里是我到目前为止的代码:
<?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;
}
?>
看起来这个应用程序可以通过将answerX列移动到它自己的表中来改善数据库结构。 – Kwebble
假设你的逻辑的其余部分是正确的,那么这应该工作:'$ count = array_sum(array_map(function($ v){return($ v!==''&& $ v!== null?1:0); },$ new_array));' – MonkeyZeus