遍历多维对象/数组

时间:2019-07-04 07:43:26

标签: php arrays object soap iteration

我有一些肥皂API的数据。此数据以以下格式显示:

array(2) {
  ["Request"]=>
  object(stdClass)#7 (3) {
    ["AccessKey"]=>
    string(3) "dub"
    ["Timestamp"]=>
    string(19) "2019.07.04 09:06:19"
    ["Conditions"]=>
    object(stdClass)#8 (1) {
      ["Condition"]=>
      object(stdClass)#9 (2) {
        ["Field"]=>
        string(11) "From"
        ["Value"]=>
        string(10) "1562223979"
      }
    }
  }
  ["Products"]=>
  object(stdClass)#10 (1) {
    ["Product"]=>
    array(10) {
      [0]=>
      object(stdClass)#11 (11) {
        ["Ean"]=>
        string(13) "4029759107323"
        ["Type"]=>
        string(9) "DVD"
        ["Title"]=>
        string(58) "Hellraisers"
        ["FSK"]=>
        string(36) "Freigegeben ohne Altersbeschränkung"
        ["Genre"]=>
        string(5) "Sport"
        ["Year"]=>
        string(4) "2015"
        ["Length"]=>
        string(3) "275"
        ["Language"]=>
        string(7) "Deutsch"
        ["Items"]=>
        string(1) "2"
        ["Release"]=>
        string(10) "2049-12-31"
        ["Label"]=>
        string(17) "Edel Germany GmbH"
      }

我想遍历这些数据并获取每个集合的标题。

我尝试了foreach循环,但收到一些错误消息。

foreach ($results as $result) {
    echo "Titel " . $result->Titel;
}

foreach ($results as $result) {
    echo "Titel " . $result['Product']->Titel;
}

没有任何效果。我不能把头缠在数组上……

1 个答案:

答案 0 :(得分:0)

当您不掌握某些内容时,有时最好尝试将其缩小并从那里扩大,开始尝试打印整个响应,然后依次打印属性乘积,产品和乘积数组:

如何到达$response内部的产品数组

首先,您有一个对象$response,其中元素内部包含对象,["Products"]是我们想要的对象,因此$response->Products然后在["Products"]内部,有一个对象,其中有一个名称为["Product"]的属性,其中包含具有所有乘积的对象数组,因此为$response>Products->Product。由于$response->Products->Product是一个数组,我们需要对其进行迭代,因此您可以像这样迭代:

foreach($response->Products->Product as $product){
 echo $product->Title; // prints the title of every product
}

不要犹豫,问您是否不理解或不起作用,但是通过粘贴的代码,我认为foreach是正确的。

How to access a property of an object (stdClass Object) member/element of an array? [duplicate]

JSON格式建议

顺便说一句,JSON不是“清晰”和“正确”的,产品数组应该在上面一级。在“产品”中而不是在“产品”中。

相关问题