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