在PHP中循环遍历对象

时间:2017-05-17 16:05:42

标签: php arrays loops object

我在PHP :::中循环遍历对象和子对象时需要帮助  我需要每个对象数组中的[permissions]元素。


    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

    }

2 个答案:

答案 0 :(得分:0)

你有Laravel的Collection对象。阅读有关馆藏here的内容,并使用其中一种方法,例如map, filter, each ...

例如,您可以尝试:

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

答案 1 :(得分:0)

你可以使用forEach而无需转换:

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

    // do something

    }
}