2017-05-08 32 views
0

我有一個像下面給出的數組 是否有可能找到數組的鍵索引,如果我在PHP中提供一個slab id值?如何通過php中的對象數組中的屬性進行搜索?

Array 
     (
      [0] => incentiveSlab Object 
       (
        [slabId] => 1 
        [templateId] => 1 
        [startPoint] => 0 
        [endPoint] => 1000000 
        [value] => 0 
       ) 

      [1] => incentiveSlab Object 
       (
        [slabId] => 2 
        [templateId] => 1 
        [startPoint] => 1000000 
        [endPoint] => 2500000 
        [value] => 0.5 
       ) 


     ) 

回答

0

我會建議,改變你的數據結構

  • 使用slabId作爲Array_Index
  • EG。

    陣列

    [0] => NULL 
    
        [1] => incentiveSlab Object 
         (
          [slabId] => 1 
          [templateId] => 1 
          [startPoint] => 0 
          [endPoint] => 1000000 
          [value] => 0 
         ) 
    
        [2] => incentiveSlab Object 
         (
          [slabId] => 2 
          [templateId] => 1 
          [startPoint] => 1000000 
          [endPoint] => 2500000 
          [value] => 0.5 
         ) 
    

或者,如果你有slabId太多的變化使用關聯數組

3

類似的東西:

function getIndex($array, $slabId) { 
    foreach($array as $index => $item) { 
     if($item->slabId == $slabId) 
      return $index; 
    } 
} 
+0

我一直在尋找建功能 –

0

,一旦發現類似上述答案的解決方案應該返回指數。但是,如果沒有匹配,它應該返回其他內容,如其他標準函數,如substr,如果不匹配則返回false。所以Max答案可能被修改,咯,是:

function getIndex($array, $slabId) { 
    foreach($array as $index => $item) { 
     if($item->slabId == $slabId) 
      return $index; 
    } 
    return false; // or return -1 
} 
相關問題