0

我有一个数组,我想找到所有值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_arrayarray_search没有运气。有什么建议么?

4

4 回答 4

0
foreach ($quiz_array as $key => $value) {
 if (strpos($value, '<name of value you want to search>') !== false) {
    $new_key = $key;
    break;
  }
}
于 2013-05-03T10:14:22.253 回答
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');
于 2013-05-03T10:29:03.593 回答
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);
于 2013-05-03T10:30:01.173 回答
0

这是你的答案,

foreach($quiz_array as $key=> $value) {
  foreach($quiz_array[$key] as $key=> $value) {
    if( $value["correct"] ) {
        echo $key ."<br>";  
    }
  }
}
于 2013-05-03T10:34:35.120 回答