2013-05-03 220 views
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,但沒有運氣。有什麼建議麼?

+1

'的foreach' ....... – zerkms 2013-05-03 10:12:12

+0

可能重複的[查找多維數組的值](http://stackoverflow.com/questions/10811908/find-values-in-multidimensional-arrays) – JJJ 2013-05-03 10:13:23

回答

0

這是你的答案,

foreach($quiz_array as $key=> $value) { 
    foreach($quiz_array[$key] as $key=> $value) { 
    if($value["correct"]) { 
     echo $key ."<br>"; 
    } 
    } 
} 
+0

謝謝,這是我需要的 – Edgar 2013-05-03 11:04:45

0
foreach ($quiz_array as $key => $value) { 
if (strpos($value, '<name of value you want to search>') !== false) { 
    $new_key = $key; 
    break; 
    } 
} 
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'); 
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);