2014-10-20 153 views
0

我有一個數組$的數據,這裏的print_r($data)值:如何獲得一個數組元素

 [ProductProperties] => Array 
      (
       [ProductProperty] => Array 
        (
         [0] => Array 
          (
           [Additionaldescription] => microphone, blabla 
          ) 

         [1] => Array 
          (
           [interface] => USB 2.0 
          ) 

         [2] => Array 
          (
           [Model] => C310 HD 
          ) 

         [3] => Array 
          (
           [Manufacturer] => Logitech 
          ) 

         [4] => Array 
          (
           [Color] => Black 
          ) 

        ) 

      ) 

如果我想顯示「接口」的價值,我必須做這樣的:

echo $data['ProductProperties']['ProductProperty'][0]['interface']; 

但在我的情況下,這些數字總是在變化,所以使用上述方法是不行的。我可以直接選擇「界面」值而不提及數字索引,例如:

echo $data['ProductProperties']['ProductProperty']['interface']; 

在此先感謝。 (使用php 5.5)

回答

0

不,你不能,除非你手動編寫一個函數它。您將不得不遍歷要搜索的數組,並使用array_key_exists函數來檢查該密鑰的存在。

一個小片段,這將幫助你前進的道路:

foreach($data['ProductProperties']['ProductProperty'] as $array) 
    if(array_key_exists("KEY_TO_SEARCH_FOR", $array)) 
    return $array; 
4

不,你不能以你寫的方式。您必須遍歷整個$data['ProductProperties']['ProductProperty']數組,並檢查嵌套數組中是否存在interface鍵。

0

沒有,但你可以寫你的函數走出interface

$interface = getInterFace($data['ProductProperties']['ProductProperty']); 

function getInterFace($array) { 
    foreach ($array as $element) { 
     if (isset($element['interface'])) { 
      return $element['interface']; 
     } 
    } 
    return false; 
}