2017-02-28 101 views
2

如何找到具有適當值的disciplines的鍵陣列?
例如:陣列中的搜索陣列輸入鍵

$arr1 = [2, 4, 12]; 
$result = [...] // Var_dump in link 
in_array($arr1, $result); 

不管它們的順序,我要看看是否有一組鍵或沒有。 但是in_array()不起作用。 謝謝!

Dump array


更新(2017年3月1日)

這是我的版本解決的這個問題

$findResult = array_filter($result, function($val)use($get){ 
      $requiredDisciplines = [1, $get['disciplines']['second'], $get['disciplines']['third'], $get['disciplines']['four']]; // запрос 
      $activePriorities = []; 

      foreach ($val['disciplines'] as $discipline) { 
       if (in_array($discipline['id'], $requiredDisciplines)) { 
        $activePriorities[] = $discipline['priority']; 
       } 
      } 

      for ($i = 0; $i<3; $i++){ 
       if(!in_array($i, $activePriorities)) 
        return false; 
      } 

      /*if(in_array(0, $activePriorities) && in_array(1, $activePriorities) && in_array(2, $activePriorities) != true) 
       return false;*/ 

      // print_r($activePriorities); 

      return true; 
     }); 
+0

問題還不清楚......學科在哪裏定義......? – Naincy

+1

in_array()不適用於php中的多維數組.... –

+0

@Naincy,如果數組中存在一組規則,我需要得到一個答案true或false。 例如:$學科[2,4,12]; – ladone

回答

3

我有一個多功能的一行即會給你所有包含匹配的數組。 (所以你可以從中得到鑰匙或計數)。 (demo

此功能僅設置爲在針和乾草堆之間比較值,但可以通過用array_intersect_assoc替換array_intersect和添加,ARRAY_FILTER_USE_BOTH到的端部被設置爲檢索關鍵字值對過濾器功能(參考文獻:第二代碼段@https://stackoverflow.com/a/42477435/2943403

<?php 
// haystack array 
$result[]=array(1,2,3,4,5,6,7,8,9,10,11,12); 
$result[]=array(1,3,5,7,9,11); 
$result[]=array(2,4,6,8,10,12); 

// needle array 
$arr1=array(2,4,12); 

//one-liner: 
$qualifying_array=array_filter($result,function($val)use($arr1){if(count(array_intersect($val,$arr1))==count($arr1)){return $val;}}); 

/* 
// multi-liner of same function: 
$qualifying_array=array_filter(
    $result, 
    function($val)use($arr1){ // pass in array to search 
     if(count(array_intersect($val,$arr1))==count($arr1)){ // total pairs found = total pairs sought 
      return $val; 
     } 
    } 
);*/ 


echo 'Total sub-arrays which contain the search array($arr1): ',sizeof($qualifying_array),"<br>"; 
echo 'Keys of sub-arrays which contain the search array($arr1): ',implode(',',array_keys($qualifying_array)),"<br>"; 
echo 'Is search array($arr1) in the $result array?: ',(sizeof($qualifying_array)?"True":"False"),"<br>"; 
echo "<pre>"; 
print_r($qualifying_array); 
echo "</pre>"; 

輸出:

Total sub-arrays which contain the search array($arr1): 2 
Keys of sub-arrays which contain the search array($arr1): 0,2 
Is search array($arr1) in the $result array?: True 
Array 
(
    [0] => Array 
     (
      [0] => 1 
      [1] => 2 
      [2] => 3 
      [3] => 4 
      [4] => 5 
      [5] => 6 
      [6] => 7 
      [7] => 8 
      [8] => 9 
      [9] => 10 
      [10] => 11 
      [11] => 12 
     ) 

    [2] => Array 
     (
      [0] => 2 
      [1] => 4 
      [2] => 6 
      [3] => 8 
      [4] => 10 
      [5] => 12 
     ) 

) 
+0

它看起來像我的問題的解決方案。但是,我發現自己是你的問題的答案!謝謝你的回答! – ladone