对象的子数组上的If语句


If statement on a sub array of an object

希望这个标题有意义,但我的问题是我有一个带有这样数组的对象,这只是数组中的1作为示例

    object(stdClass)#6 (3) {
  ["items"]=>
  array(40) {
    [0]=>
    object(stdClass)#7 (22) {
      ["id"]=>
      int(46)
      ["parentId"]=>
      int(0)
      ["name"]=>
      string(22) "Complete monthly wages"
      ["description"]=>
      string(294) "Complete monthly wages<span style=""></span><br /><div>Complete monthly wages<span style=""></span><br /></div><div>Complete monthly wages<span style=""></span><br /></div><div>Complete monthly wages<span style=""></span><br /></div><div>Complete monthly wages<span style=""></span><br /></div>"
      ["tags"]=>
      string(0) ""
      ["projectId"]=>
      int(12)
      ["ownerId"]=>
      int(1)
      ["groupId"]=>
      int(0)
      ["startDate"]=>
      string(19) "2012-09-03T00:00:00"
      ["priority"]=>
      int(2)
      ["progress"]=>
      float(0)
      ["status"]=>
      int(10)
      ["createdAt"]=>
      string(19) "2012-09-03T07:35:21"
      ["updatedAt"]=>
      string(19) "2012-09-03T07:35:21"
      ["notifyProjectTeam"]=>
      bool(false)
      ["notifyTaskTeam"]=>
      bool(false)
      ["notifyClient"]=>
      bool(false)
      ["hidden"]=>
      bool(false)
      ["flag"]=>
      int(0)
      ["hoursDone"]=>
      float(0)
      ["estimatedTime"]=>
      float(0)
      ["team"]=>
      object(stdClass)#8 (3) {
        ["items"]=>
        array(2) {
          [0]=>
          object(stdClass)#9 (1) {
            ["id"]=>
            int(2)
          }
          [1]=>
          object(stdClass)#10 (1) {
            ["id"]=>
            int(1)
          }
        }
        ["count"]=>
        int(2)
        ["total"]=>
        int(2)
      }
    }

正如我们所看到的,它有一个团队部分,这是我的重点

["team"]=>
          object(stdClass)#8 (3) {
            ["items"]=>
            array(2) {
              [0]=>
              object(stdClass)#9 (1) {
                ["id"]=>
                int(2)
              }
              [1]=>
              object(stdClass)#10 (1) {
                ["id"]=>
                int(1)
              }
            }
            ["count"]=>
            int(2)
            ["total"]=>
            int(2)
          }
        }

正如你所看到的,那里有2个id,1和2,可能有30个左右的id,但我不知道如何有效地告诉它搜索整个数组。

如果我使用这个,只要Id 1恰好是Id中的第一个项目,它就可以工作,但显然并不总是这样。我的目标是搜索对象,如果用户ID在团队数组中,只需运行代码,我对php和对象特别陌生,所以希望有人能给我指明正确的方向

foreach($tasksList->items as $task_details) 
{
    if($task_details->team->items->id === 1)
    {
        echo "My Code";
    }

}

您的代码(以及上面粘贴的[team]部分)似乎忽略了team->items数组这一事实。在顶部样本中,它看起来像:

["team"]=>
  object(stdClass)#8 (3) {
    ["items"]=>
    /* It's an array! */
    array(2) {
     ...
    }
  }

它不会直接具有id属性。相反,您需要迭代team->items:

foreach ($taskList->items as $task_details) {
  foreach ($task_details->team->items as $key => $value) {
    echo "Team item #: $key ... Team id: $value->id'n";
    if ($value->id === 1) {
       echo "Matched Team ID 1'n";
    }
  }
}