2017-05-17 174 views
0

我需要幫助循環遍歷PHP中的對象和子對象::: 我需要每個對象數組中的[permissions]元素。循環遍歷PHP中的對象

 

    object(Illuminate\Support\Collection)#21 (1) { 
     ["items":protected]=> 
     array(5) { 
     [0]=> 
     object(Discord\OAuth\Parts\Guild)#31 (5) { 
      ["id"]=> 
      string(17) "41771983423143937" 
      ["name"]=> 
      string(18) "Discord Developers" 
      ["icon"]=> 
      string(32) "edc44e98a690a1f76c5ddec68a0a6b9e" 
      ["owner"]=> 
      bool(false) 
      ["permissions"]=> 
      int(104139776) 
     } 
     [1]=> 
     object(Discord\OAuth\Parts\Guild)#22 (5) { 
      ["id"]=> 
      string(17) "81384788765712384" 
      ["name"]=> 
      string(11) "Discord API" 
      ["icon"]=> 
      string(32) "a8eccf1628b1e739d535a813f279e905" 
      ["owner"]=> 
      bool(false) 
      ["permissions"]=> 
      int(104189120) 
     } 
     [2]=> 
     object(Discord\OAuth\Parts\Guild)#37 (5) { 
      ["id"]=> 
      string(18) "159962941502783488" 
      ["name"]=> 
      string(12) "Mee6 The Bot" 
      ["icon"]=> 
      string(32) "18fbd59f2df5133bf2ec8b2d8f231a73" 
      ["owner"]=> 
      bool(false) 
      ["permissions"]=> 
      int(37080065) 
     } 
     [3]=> 
     object(Discord\OAuth\Parts\Guild)#23 (5) { 
      ["id"]=> 
      string(18) "203646825385689090" 
      ["name"]=> 
      string(6) "Jeeves" 
      ["icon"]=> 
      string(32) "77f447fb171964e1e61f706165d9f601" 
      ["owner"]=> 
      bool(false) 
      ["permissions"]=> 
      int(104193089) 
     } 
     [4]=> 
     object(Discord\OAuth\Parts\Guild)#36 (5) { 
      ["id"]=> 
      string(18) "314050405283921920" 
      ["name"]=> 
      string(7) "tesssst" 
      ["icon"]=> 
      NULL 
      ["owner"]=> 
      bool(true) 
      ["permissions"]=> 
      int(2146958591) 
     } 
     } 
    } 

基本上我需要在每個[permissions]元素上使用if條件執行一次明智的操作檢查。

 

    if((32 & [permissions]) !== 0) { 

    // do something 

    } 

+0

您不能訪問項目數組,因爲它是'protected'。檢查'Illuminate \ Support \ Collection'對象的定義,它可能有一個你可以使用的getter方法,或者可能實現一個像'ArrayAccess'這樣的接口。 –

+0

@AlexHowansky,謝謝,你的回答也有幫助。 –

回答

0

您在這裏Laravel的Collection對象。閱讀關於集合here和使用它的方法之一,像map, filter, each ...

例如,你可以嘗試:

$collection->each(function ($item, $key) { 
    if ((32 & $item->permissions) !== 0) { 
     // do something 
    } 
}); 
0

您可以用foreach做到無需轉換:

foreach ($yourobject->item as $obj) { 
    if((32 & $obj->permissions) !== 0) { 

    // do something 

    } 
}