2017-07-19 40 views
0

試圖查找數組中是否存在值。這裏的問題是,我從websercive獲取數組,我可以得到的結果早在兩種格式在php數組中查找退出

格式1:

[SubCategory] => Array 
     (
      [RefSubCategory] => normalPhoto 
      [NameSubCategory] => normalPhoto 
      [Description] => ד 
      [Order] => 2 
     ) 

格式2

[SubCategory] => Array 
     (
      [0] => Array 
       (
        [RefSubCategory] => Enlargement 
        [NameSubCategory] => Enlargement 
        [Description] => Enlargement 
        [Order] => 1 
       ) 

      [1] => Array 
       (
        [RefSubCategory] => normalPhoto 
        [NameSubCategory] => normalPhoto 
        [Description] => ד 
        [Order] => 2 
       ) 

     ) 

感謝您的幫助。

回答

1
if(isset($SubCategory[0])){ //Format 2 
    //search in each sub array for the value 
    foreach($SubCategory as $key => $subarray){ 
     if(in_array($valtofind,$subarray)){ 
      echo "Value found in SubCategory[$key]"; 
     } 
    } 
} else { //otherwise it's Format 1 so just search for the value 
    if(in_array($valtofind,$SubCategory)){ 
     echo "Value found in SubCategory"; 
    } 
} 
+2

您不認爲這會爲第一類結果的is_array($ SubCategory [0])創建一個錯誤「undefined index 0」。 –

+0

不,因爲如果'$ SubCategory [0]'不是數組,那麼它是一個帶有'RefSubCategory'鍵的字符串。至少基於OP的例子。 – WheatBeak

+0

它確實產生了一個錯誤 –