【问题标题】:php stdClass accessphp stdClass 访问
【发布时间】:2012-11-05 14:37:54
【问题描述】:

我有这样的输出:

stdClass Object
(
    [GetMatchdataByLeagueDateTimeResult] => stdClass Object
        (
            [Matchdata] => Array
                (
                    [0] => stdClass Object
                        (
                            [teamId] => 40

在 foreach 循环中

foreach ($allMatches as $match):

我现在希望使用如下数据:

if ($match->idTeam1 == $teamId || $match->idTeam2 == $teamId):

但我得到这个错误:

试图获取非对象的属性

原因是,Matchdata 数组包含大约 60 多个条目,我想过滤掉 [idTeam1][idTeam2] == 给定 id 的条目。

结果我应该只得到大约 5 到 7 个条目。

在使用 stdClass 对象时,最好的方法是什么?

请帮忙!

谢谢!!

【问题讨论】:

  • idTeam1idTeam2 声明在哪里?你的对象结构是什么?
  • 您的输出示例(假设它是 $allMatches?)与您的伪代码不匹配。 teamId vs idTeam1 - idTeam1 来自哪里?
  • $match[0]->idTeam1 工作吗?
  • 不是 100% 确定,但您似乎需要使用 gettype() PHP 函数测试变量类型:php.net/manual/en/function.gettype.php
  • ...您使用对象而不是关联数组有什么原因吗?

标签: php arrays object stdclass


【解决方案1】:

假设$response 是您发布的结构:

$teamId = 99; // target teamId

foreach($response->GetMatchdataByLeagueDateTimeResult->MatchData as $match)
{
    if ($match->idTeam1 == $teamId || $match->idTeam2 == $teamId)
    {
        // this `$match` has the target $teamId - do something
    }
}

【讨论】:

    【解决方案2】:

    好吧,我只是瞎了眼: foreach ($allMatches->GetMatchdataByLeagueDateTimeResult->Matchdata as $id => $match): 调试($id); 调试($match->idTeam1);

    现在可以了: if ($match->idTeam1 == $teamId || $match->idTeam2 == $teamId) ...

    还是非常感谢!!

    【讨论】:

      【解决方案3】:

      您的外部结构是一个对象,因此您可能正在迭代对象的可见属性(请参阅此页面)。如果你想遍历对象实例中的数组,你应该将它传递给你的 foreach 循环,或者让你的类实现 Iterator 接口并将其方法重定向到数组。

       <?php
             foreach ($object->allMatches as $match) {
                    /* Your iterate body here */
             }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-22
        • 2016-11-12
        • 2014-10-17
        • 2011-08-07
        • 2013-01-25
        • 2015-06-18
        • 2012-06-24
        相关资源
        最近更新 更多