2017-07-25 81 views
1

我需要檢查值是否存在於數組中,一旦存在,我需要獲取該對象。檢查是否存在值,並返回多維數組中的對象

Array 
(
    [0] => Array 
     (
      [_id] => Array 
       (
        [purok] => test 
        [year] => 2017 
        [options] => below-1 
       ) 

      [data] => Array 
       (
        [58cf4935572d6e32900057ab] => Array 
         (
          [age-sex-distribution] => Array 
           (
            [age-range] => Array 
             (
              [options] => below-1 
             ) 

            [gender] => Array 
             (
              [male-distribution-count] => 12 
              [female-distribution-count] => 12 
             ) 

           ) 

         ) 

       ) 

      [date] => 2017-07-08 
     ) 

    [1] => Array 
     (
      [_id] => Array 
       (
        [purok] => test 
        [year] => 2017 
        [options] => toddlers (1-2) 
       ) 

      [data] => Array 
       (
        [58cf4935572d6e32900057ab12] => Array 
         (
          [age-sex-distribution] => Array 
           (
            [age-range] => Array 
             (
              [options] => toddlers (1-2) 
             ) 

            [gender] => Array 
             (
              [male-distribution-count] => 12 
              [female-distribution-count] => 12 
             ) 

           ) 

         ) 

       ) 

      [date] => 2017-07-08 
     ) 

) 

如果存在,我需要檢查這個[options] => below-1。其中一個存在,我需要在陣列中獲得data

到目前爲止,我已經嘗試過這一個。

$keySearch = "data.options"; 
$dataOption = array_search("below-1", array_column($rec, $keySearch)); 
print_r($dataOption); 

但沒有結果。

感謝您提前幫助我。

回答

1
$temp = []; 

for ($data as $value){ 
    if($value['_id']['options'] == 'below-1'){ 
     $temp[] = $value; 
    } 
} 

print_r($temp); 

你可以試試這個

1

試試這個:

function search_array($needle, $haystack) { 
    if(in_array($needle, $haystack)) { 
      return true; 
    } 
    foreach($haystack as $element) { 
      if(is_array($element) && search_array($needle, $element)) 
       return true; 
    } 
    return false; 
} 

if(!search_array($value, $array)) { 
    // do something if the given value does not exist in the array 
}else{ 
    // do something if the given value exists in the array 
} 
1

你應該試試這個:

for($i=0; $i < count($rec); $i++) { 
    if ($rec[$i]['_id']['options'] === "below-1") { 
      $dataOption = $rec[$i]['data']; 
      break; 
    } 
} 
print_r($dataOption); 

它應該做你期待什麼;-)

相關問題