我有一个数组,我想找到correct => true
:
$quiz_array = array (
'question1' => array (
'q1a1' => array (
'correct' => FALSE,
'answer' => 'false answer1'
),
'q1a2' => array (
'correct' => FALSE,
'answer' => 'false answer2'
),
'q1a3' => array (
'correct' => FALSE,
'answer' => 'false answer3'
),
'q1a4' => array (
'correct' => TRUE,
'answer' => 'correct answer'
)
)
);
我想进行搜索,在这种情况下会返回q1a4
,因为correct => TRUE
。我使用in_array
和array_search
进行了尝试,但没有运气。有什么建议吗?
答案 0 :(得分:0)
foreach ($quiz_array as $key => $value) {
if (strpos($value, '<name of value you want to search>') !== false) {
$new_key = $key;
break;
}
}
答案 1 :(得分:0)
你可以这样做:
$correctAnswers = array();
foreach ($quiz_array as $question => $answers) {
$correctAnswers[$question] = array_filter($answers, function($v) {
return $v['correct'];
});
}
var_dump($correctAnswers); // array('question1' => array('q1a4' => array('correct' => true, 'answer' => 'correct answer')));
如果您想返回只是正确的答案key
(例如q1a41
),您可以这样做:
$correctAnswers = array();
foreach ($quiz_array as $question => $answers) {
foreach ($answers as $k => $a) {
if ($a['correct']) {
$correctAnswers[$question] = $k;
}
}
}
var_dump($correctAnswers); // array('question1' => 'q1a4');
答案 2 :(得分:0)
function correct($array) {
return $array('correct');
}
$results= array();
foreach($quiz_array as $key => $value) {
$correct= array_filter($value, 'correct');
$results[$key]= $correct;
}
print_r($results);
答案 3 :(得分:0)
这是你的答案,
foreach($quiz_array as $key=> $value) {
foreach($quiz_array[$key] as $key=> $value) {
if( $value["correct"] ) {
echo $key ."<br>";
}
}
}