PHP删除数组内的对象

时间:2016-04-18 11:50:52

标签: php

在将数据发送到视图

之前,我必须删除操作中的一些对象

数据是这样的:

'items' => [
        (int) 0 => object(App\Model\Entity\Propriete) {

        'id_propriete' => (int) 1,
         // and other fields
        'user' => object(App\Model\Entity\User) {

            'id' => '1459436853',
        //and other fields
        },
        'favorites' => [
            (int) 0 => object(App\Model\Entity\Favorite) {

                'id' => (int) 24,
                'propriete_id' => (int) 1,
                'user_id' => '1459438630',
                'created' => object(Cake\I18n\FrozenDate) {

                    'time' => '2016-04-15T00:00:00+00:00',
                    'timezone' => 'UTC',
                    'fixedNowTime' => false

                },
                'modified' => object(Cake\I18n\FrozenDate) {

                    'time' => '2016-04-15T00:00:00+00:00',
                    'timezone' => 'UTC',
                    'fixedNowTime' => false

                },

            },
            (int) 1 => object(App\Model\Entity\Favorite) {

                'id' => (int) 27,
                'propriete_id' => (int) 1,
                'user_id' => '1459436853',
            ,
                'modified' => object(Cake\I18n\FrozenDate) {

                    'time' => '2016-04-18T00:00:00+00:00',
                    'timezone' => 'UTC',
                    'fixedNowTime' => false

                },
                '[new]' => false,
                '[accessible]' => [
                    '*' => true
                ],
                '[dirty]' => [],
                '[original]' => [],
                '[virtual]' => [],
                '[errors]' => [],
                '[invalid]' => [],
                '[repository]' => 'Favorites'

            },
            (int) 2 => object(App\Model\Entity\Favorite) {

                'id' => (int) 28,
                'propriete_id' => (int) 1,
                'user_id' => 'ae0dce23-584b-4907-b32e-1655d5e69e55',


            }
        ],
    }
]

收藏夹是一个数组,我想根据条件删除此数组中的某些特定对象。 这就是我试图做的事情:

   foreach($proprietes as $ad){
      foreach($ad->favorites as $favori)
          if($favori->user_id !==$user['id']){
              unset($favori);
          }
   }

Butit不起作用可以帮助吗?

1 个答案:

答案 0 :(得分:1)

   foreach($proprietes as $ad){
      foreach($ad->favorites as $key=>$favori)
          if($favori->user_id !==$user['id']){
              unset($ad->favorites[$key]);
          }
   }

您必须直接引用该对象。